任何人都可以解釋爲什麼下面的代碼在Visual Studio 2015 C++中出現錯誤「錯誤C2259:'PropertyValue':無法實例化抽象類」?在派生模板類中用條件類型特徵覆蓋基類中的虛方法
編譯器無法識別派生類PropertyValue
中的條件指定函數ConvertToDevice()
是否具有相同的簽名?
非常感謝,
約翰
#include <type_traits>
#include <typeinfo>
class BasePropertyValue
{
public:
virtual int ConvertToDevice(void** ptrdObject) = 0;
};
template<typename T> class PropertyValue : public BasePropertyValue
{
public:
T value;
PropertyValue(T val)
{
value = val;
}
template<class Q = T>
typename std::enable_if<!std::is_pointer<Q>::value, int>::type ConvertToDevice(void** ptrdObject)
{
return 1;
}
template<class Q = T>
typename std::enable_if<std::is_pointer<Q>::value, int>::type ConvertToDevice(void** ptrdObject)
{
return 2;
}
};
void main()
{
PropertyValue<double>* prop1 = new PropertyValue<double>(20);
prop1->ConvertToDevice(nullptr);
double x = 20;
PropertyValue<double*>* prop2 = new PropertyValue<double*>(&x);
prop2->ConvertToDevice(nullptr);
return;
}
[編輯]這不是一個重複的問題,因爲條件性狀方面的。
一個好的技巧是始終聲明函數'override'您打算要重寫;那麼如果你實際上沒有覆蓋任何東西,你將會遇到編譯器錯誤 – Justin
當你[添加'override'關鍵字](https://godbolt.org/g/ue7EGk)時,編譯器很好的解釋了爲什麼這樣做不工作:「成員模板...可能沒有virt-specifiers」。基本上,你不能混用虛函數和模板 – Justin
[C++類的成員函數模板可以虛擬嗎?](https://stackoverflow.com/questions/2354210/can-ac-class-member-function- template-be-virtual) – Justin