我试图将多态性与模板化派生类一起使用 . 请考虑以下代码:
// base class
class A {
public:
virtual void f() = 0;
};
// templated derived class
template< typename T >
class B : public A {};
template <> //define a specialization of B
class B< int > {};
// trying to define a specialization of f
template <>
void B< int >::f() {}
我的基类有纯虚函数 f
. 我存储了一个基类指针 A*
的向量,并希望在所有这些上调用 f
,并在模板化派生类上使用适当的多态性 . 但是,我无法定义f的特化,因为我收到以下错误:
test.cpp:17:18: error: no member function ‘f’ declared in ‘B<int>’ void B< int >::f() {}
显然,这里的错误是 f
实际上并不是模板化类的成员函数 . 有没有办法定义f的特化(或几乎等价的东西),或者这根本不可能?如果不可能,你能提出另一种方法吗?
[道歉,如果这是重复的 - 我搜索并发现了许多关于模板,继承和多态的问题,但没有一个与我的完全匹配 . ]
1 回答
您的专业化未定义覆盖虚拟函数 . 将此专业化更改为:
专业化就像定义一个新类 . 你必须定义其中的所有内容 . 如果专业化应该有一个特定的方法:定义它 .
编辑:还纠正了从原始问题继承的错字 .