Search code examples
c++templatesderived-classbase-classfunction-templates

specification of function templates


I would like to create a function template where the class T is limited to only derived classes of a special base class T_base. What is the efficient way to accomplish this? Thanks for your help!


Solution

  • You can use type traits and SFINAE

    template<typename T, 
             bool[std::is_base_of<T_base, T>::value] = nullptr>
    void f(T const&);
    

    C++03 version that also works for C++11

    template<typename T>
    typename boost::enable_if< boost::is_base_of<T_base, T> >::type 
    f(T const&);
    

    There is the C++11 version of moving the enable_if into the template parameter list, using a default argument

    template<typename T, 
             typename = typename std::enable_if<
               std::is_base_of<T_base, T>::value>::type>
    void f(T const&);
    

    Sadly you then cannot overload f if the only difference of your other overload is the SFINAE string (i.e the default argument), because the default argument is not part of the signature of a function template. But the type of the template parameters themselfs are (these rules are just like for normal function parameters).