我正在尝试将多态性与模板派生类一起使用。考虑以下代码:
// 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*
的 vector ,并希望对所有这些指针调用 f
,并在模板派生类上使用适当的多态性。但是,我无法定义 f 的特化,因为我收到以下错误:
test.cpp:17:18: error: no member function ‘f’ declared in ‘B<int>’ void B< int >::f() {}
显然这里的错误是 f
实际上不是模板类的成员函数。有什么方法可以定义 f 的特化(或几乎等效的东西),或者这根本不可能吗?如果不可能,您能否建议另一种方法?
[如果这是重复的,我深表歉意——我搜索并发现了很多关于模板、继承和多态性的问题,但没有一个与我的完全匹配。]
最佳答案
template <> //define a specialization of B
class B< int > {};
您的特化没有定义被覆盖的虚函数。将此专业更改为:
template <> //define a specialization of B
class B< int > : public A
{
public:
void f() override;
}
特化就像定义一个新类。您必须定义其中的所有内容。如果特化应该有一个特定的方法:定义它。
编辑:还更正了从原始问题继承的错字。
关于c++ - 具有模板化派生类的基类纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403198/