C++ – Can a class member function template be virtual


I have heard that C++ class member function templates can't be virtual. Is this true?

If they can be virtual, what is an example of a scenario in which one would use such a function?

Best Solution

Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.

Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.

However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.