0

Why does the following code work if virtual is not allowed on class template member functions?

template <typename T>
class Test {

public:

    virtual ~Test() {}  
    virtual void Func(const T&) {}
};
user963241
  • 6,015
  • 16
  • 59
  • 86

4 Answers4

4

...if virtual is not allowed on class template member functions?

I think the issue here is terminological ambiguity:

  • It is perfectly permissible to have virtual functions inside class templates. In fact, it could be a requirement that Test<T>'s destructor is virtual if you were to subclass Test<T> and delete instances of the subclass through pointers to Test<T>. See When to use virtual destructors? for an extended discussion.

  • What you can't do is make function templates virtual. See Can a C++ class member function template be virtual?

Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970
4

You have some answers already that explain what's valid and what isn't, but let me try to word it differently to explain the confusion:

"class template member functions" is ambiguous. It could mean member functions of a class template, or it could mean template member functions of a class. The former can be virtual (as long as they themselves are not template member functions), the latter cannot.

It seems as if someone claimed virtual is not allowed on class template member functions, and meant template member functions of a class, but you interpreted it differently.

3

You cannot have templated virtual member functions(more here). What you have is a template class with a virtual member function which is completely fine.

Community
  • 1
  • 1
Pradhan
  • 15,095
  • 3
  • 39
  • 56
3

the code will not not compile if you use this syntax:

template <typename T> virtual Func(const T&){}

This has not a meaning as virtual function are bounded at runtime to allow dynamic polymorphism but if a function is a template one it's meant to be instantiated at compile time (static polymorphism). In your case your function is not a template one so it can be declared virtual inside your template class.

Mohamed Ali
  • 173
  • 5