你好我有部分專業化的問題。我想要做的是擁有一個具有模板成員函數的類,該函數將給定的值解釋爲用戶指定的值。例如類名是Value
,這裏是什麼,我想做一個片段:在爲類方法做指針部分特化時獲取「非法使用顯式模板參數」
int *ptr1 = new int;
*ptr1 = 10;
Value val1 = ptr1;
int *ptr2 = val1.getValue<int*>();
Value val2 = 1;
int testVal = val2.getValue<int>();
這裏是我是如何實現這樣的類:
struct Value {
Value(void *p) : val1(p){}
Value(int i) : val2(i){}
template<typename T>
T getValue();
void *val1;
int val2;
};
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
template<>
int Value::getValue<int>() {
return val2;
}
當我編譯我得到以下錯誤:
error C2768: 'Value::getValue' : illegal use of explicit template arguments
基本上其抱怨代碼的指針模板部分:
template<typename T>
T* Value::getValue<T*>() {
return reinterpret_cast<T*>(val1);
}
我知道這個問題可以用一個簡單的聯合來實現,但這種代碼是一個更大的代碼是簡化版。
有人知道問題可能是什麼?我想要做的是在使用指針時使用單獨的代碼,而在不使用指針時使用其他代碼。我真的被困住了,我總是在調查而不是問,但是我還沒有找到任何有關它的好信息。
功能模板不能部分專用;只有類模板可以。 – Angew 2013-04-22 18:51:13
好吧,那可能就是這樣。我記得在C++ Modern Design中閱讀過它,它的功能不能偏袒。我認爲,因爲會員在班級的一部分中可以擺脫它。我想不是:(謝謝:D – Kunashu 2013-04-22 18:56:07