我想通過它的模板參數的類型特徵來專門化模板類上的成員函數,但是我的前向聲明顯然是不正確的。有一個簡單的解決方法嗎?按類型專門化模板類成員函數
#include <type_traits>
template <typename T>
class TTest{
public:
T data;
// edited to comment this out, template<typename U>
bool operator !=(const TTest& other) const;
};
template <typename T>
typename std::enable_if<std::is_unsigned<T>::value, bool>::type
TTest<T>::operator !=(const TTest<T>& other) const{
return true;
}
template<typename T>
bool TTest<T>::operator !=(const TTest<T>& other) const{
return false;
}
int main(){
TTest<size_t> t1;
TTest<int> t2;
}
鏘告訴我:
templateTest.cpp:13:11: error: out-of-line definition of 'TTest::operator!='
differs from the declaration in the return type
TTest<T>::operator !=(const TTest<T>& other) const{
^
templateTest.cpp:8:8: note: previous declaration is here
bool operator !=(const TTest& other) const;
^
1 error generated.
此代碼沒有意義。成員模板對模板參數具有* no *依賴性,所以沒有什麼特別的。 –
你是否意識到'const TTest&other'是指你rmember模板中的'const TTest&other'? –
你不能部分地專門化一個函數模板。如果你想要一個無符號T和非無符號T的版本,那麼你需要重載+ SFINAE或部分專門化整個類模板。 – dyp