C++:“函数模板“中对“非类型参数”作偏特化时遇到的问题

在使用 “函数模板“对“非类型参数”作偏特化时遇到编译报错的问题,代码及报错信息如下

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;
    };
};

参考文档

Why Not Specialize Function Templates?

为什么我们不建议使用函数模板具体化

猜你喜欢

转载自blog.csdn.net/netyeaxi/article/details/83473946