Reputation: 7038
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&) {}
};
Upvotes: 0
Views: 96
Reputation: 173
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.
Upvotes: 3
Reputation:
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.
Upvotes: 4
Reputation: 500167
...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?
Upvotes: 4