Search code examples
c++templatesderived-class

Function templates and derived classes


If this code, why does foo(d) call the template function rather than the 'base' function? Is there a way of getting it to call the base function without explicitly writing another function overload?

template <class T> void foo(T val)
{
    printf("template called\n");
}

class Base
{
};

void foo(const Base &val)
{
  printf("Base called\n");
}

class Derived : public Base
{   
};

int main() {
    Derived d;
    foo(d);
    return 0;
}

Solution

  • why does foo(d) call the template function rather than the 'base' function?

    Because for the template function foo T is deduced as Derived, then it's an exact match. For the non-template one a derived-to-base conversion is required.

    You can do it with SFINAE; make the function template works only with types which are not derived from Base (or Base itself).

    template <class T> 
    std::enable_if_t<!std::is_base_of_v<Base, T>> foo(T val)
    {
        printf("template called\n");
    }
    

    LIVE