我如何专门化在基类中定义为纯函数的模板化函数?
struct A {
virtual void func(int a) = 0;
//virtual void func(int a) {} // replace above line with this and it works
};
struct B : public A {
template<typename T> void func(T t) {
cout <<"hello"<<endl;
}
};
template<> void B::func<int>(int a) { cout <<"hello 2"<<endl; }
int main() {
B b;
b.func(2);
}
错误:
error: variable type 'B' is an abstract class B b; ^ note: unimplemented pure virtual method 'func' in 'B' virtual void func(int a) = 0;
最佳答案
虚函数只能被非模板函数覆盖。在这种情况下,
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
注意函数模板不能是virtual functions ;
Functions templates cannot be declared virtual.
来自标准,[temp.mem]/4
A specialization of a member function template does not override a virtual function from a base class. [ Example:
class B { virtual void f(int); }; class D : public B { template <class T> void f(T); // does not override B::f(int) void f(int i) { f<>(i); } // overriding function that calls the template instantiation };
— end example ]
关于你的问题,
why it works if the function is made 'not pure'?
编译错误消失了,但它仍然没有像你预期的那样工作;派生类中的函数模板不会覆盖基类的虚函数。你可以用 dynamic dispatch 查看:
If a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class.
请注意,您应该使用指针或引用来使动态调度工作,例如
B b;
A* pa = &b;
pa->func(2);
您也可以申请override specifier帮助您确认覆盖。
关于c++ - 纯虚函数的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954318/