我最近在C++中發現了template specialization
。成員函數的模板專精
template <typename T>
void fct(void) {}
template <>
void fct<int>(void) {}
int main(void) {
fct<int>();
return 0;
}
我想爲類中的成員函數使用模板特化。
class MyClass {
public:
template <typename T>
static void fct(void) {}
template <>
static void fct<int>(void) {}
};
int main(void) {
MyClass::fct<int>();
return 0;
}
不幸的是,g++
編制給了我以下錯誤:
error: explicit specialization in non-namespace scope ‘struct MyClass’
error: template-id ‘toto<int>’ in declaration of primary template
我發現,這樣做模板特主作用域或命名空間,但不是在一個結構或一類作品。
我發現在計算器講講下面的代碼使用一個命名空間,如:
namespace myNameSpace {
template <typename T>
void fct(void) {}
template <>
void fct<int>(void) {}
}
class MyClass {
public:
template <typename T>
static void fct(void) {
myNameSpace::fct<T>();
}
};
int main(void) {
MyClass::fct<int>();
return 0;
}
我在做什麼錯?是否可以使用成員函數進行模板專門化?如果沒有,解決這個問題的最好方法是什麼?有沒有更好的方法比使用命名空間來解決這個問題?
添加在全球範圍的成員函數的專業化如圖[這裏](http://stackoverflow.com/questions/7582548/understanding-c-member-功能模板專業化) –