Passing a derived class to a template function specialized with base class

前端 未结 4 438
悲哀的现实
悲哀的现实 2021-01-14 20:54

The following code compiles fine, but produces a linker error:

class Base {};

class Derived : public Base {};

template 
void f(const T&am         


        
4条回答
  •  暖寄归人
    2021-01-14 21:41

    Like the others have said, you haven't defined the generic template function, which is the best candidate for the derived type. If you want to better understand how template function overload resolution works, consult this reference here: http://en.cppreference.com/w/cpp/language/function_template#Function_template_overloading

    Your example is a bit contrived (perhaps for brevity's sake). But in general, you should only provide template specializations if you need to implement special logic for a particular type, or if you want to define your template class(es) and function(s) in a separate source file and only need/want to support certain types. Maybe this is what you're actually going for, but generics are called generics for a reason.

提交回复
热议问题