【发布时间】:2019-11-19 02:43:50
【问题描述】:
如何专门化在基类中定义为纯函数的模板化函数?
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);
}
错误:
错误:变量类型“B”是一个抽象类 乙乙; ^ 注意:“B”中未实现的纯虚方法“func” 虚拟 void func(int a) = 0;
【问题讨论】:
-
模板和虚函数不能混用。
-
我相信这不是重复的,因为覆盖是模板专用的。还要注意我只有纯虚函数有问题。
-
@Nujufas 问题有点不同,但答案是一样的。
Member function templates cannot be declared virtual. -
@StackDanny 可以接受,你能否解释一下如果函数被设为“不纯”,它为什么会起作用?
标签: c++ templates virtual-functions