在使用 “函数模板“对“非类型参数”作偏特化时遇到编译报错的问题,代码及报错信息如下
template<typename T, int size>
void toStr() {
cout << "1.---------------------" << endl;
};
template<typename T>
void toStr<T, 2>() { // error C2768: 'toStr': illegal use of explicit template arguments
cout << "2.---------------------" << endl;
};
template<>
void toStr<int, 3>() {
cout << "3.---------------------" << endl;
};
int main() {
toStr<int>();
toStr<int, 1>();
toStr<int, 3>();
return 0;
}
报错的原因是函数模板对偏特化缺少支持造成的,把经上代码改为使用类模板就没有问题了:
template<typename T, int size = 0>
struct X {
static void toStr() {
cout << "1.---------------------" <<endl;
};
};
template<typename T>
struct X<T, 1>{
static void toStr() {
cout << "2.---------------------" << endl;
};
};
template<>
struct X<bool, 2> {
static void toStr() {
cout << "3.---------------------" << endl;
};
};
参考文档