Reputation: 12610
I've been wondering, can a non-virtual member function use template parameters? IOW, should a function using template parameters be virtual?
Example:
template<int N>
class SomeClass
{
public:
SomeClass() {}
// Can this function be non-virtual?
int getValue() {
return N;
}
}
If I understand correctly, the compiler will basically generate one class for each template parameter value. In the above example, there would be multiple classes (one for each value of N) implicitly generated deriving from SomeClass
. Hence, in my understanding, getValue()
would need to be dispatched dynamically (to different instances of the function) depending on the actual (runtime) type.
I know that the compiler does not enforce those functions to be virtual, but can it do some magic or would I really have to make the function virtual to have the right instance be called via e.g. pointer?
Upvotes: 0
Views: 33
Reputation: 170045
Hence, in my understanding, getValue() would need to be dispatched dynamically (to different instances of the function) depending on the actual (runtime) type.
A type which is encoded right there in the object declaration:
SomeClass<0> s;
s.getValue();
The compiler will dispatch to SomeClass<0>::getValue
. It doesn't have to be dispatched at runtime, it's all available statically to the type system. Once a class template is instantiated to create a class, it's just like any other class. If you were to write:
SomeOtherClass c; // Not a template
s.doSomething();
The compiler knows it should dispatch to SomeOtherClass::doSomething
just the same.
Upvotes: 2