Template type check C++

前端 未结 6 745
日久生厌
日久生厌 2021-01-14 17:48

I have a template function which takes in objects. I need to determine whether the object is derived from a particular base class. If it is derived from the base class, I ne

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 18:54

    It is somewhat difficult to mix templates and inheritance.

    The trouble:

    template 
    void function(T const& t);
    
    void function(A const& a);
    

    If you use struct B: A {}:, then the template version is preferred, because no conversion is required, and it is therefore a "better" match.

    If you have access to the definition of the template version, you can use a combination of is_base_of and disable_if.

    template 
    typename boost::disable_if< boost::is_base_of >::type function(T const& t);
    

    This simple modification makes use of SFINAE, basically it generates an error when trying to instantiate function for any class derived from A and the C++ standard specifies that if a function may not be instantiated then it is to be removed from the set of overloads considered without triggering a compiler error.

    If you do not have access to the template definition of function, you're out of luck.

提交回复
热议问题