2
我正在嘗試將多態與模板派生類一起使用。考慮下面的代碼:具有模板派生類的基類純虛函數
// 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的特化(或幾乎相同的東西),或者這是不可能的?如果不可能,你能提出另一種方法嗎?
[道歉,如果這是一個重複 - 我搜查,發現對模板,繼承和多態的問題許多變化,但沒有完全相符我的。]
專業化不應該從'A'繼承嗎? – Rakete1111
謝謝,這解決了這個問題(儘管我的代碼中有一些額外的錯誤)。 @ Rakete1111是正確的,專業化需要從A繼承爲了多態性的工作,我錯過了。 – user7359309
是的,這也是另一個問題,糾正了。 –