这里是其中一个场景, 想了解其他的请绕行。
class 模板特例化:
template<typename T, int v1> class A { public: A(T value) { a = value * v1; } T a = 0; }; template<typename T> class A<T, 10> { public: A(T value) { a = value * 10; } T a = 0; }; template<int v1> class A<int, v1> { public: A(int value) { a = value * v1; } int a = 0; };
function 模板特例化:
报错 非法使用显式模板参数 情景如下:
template <typename T, int v1, int v2> int haha(T a) { return a * v1 * v2; } template <int v1, int v2> int haha<int, v1, v2>(int a) { return a * v1 * v2; }
理解是函数是多参数的情景, 当某个类型特例化, 那就是那个参数类型定了, 无需套用之前的模板:
template <typename T, int v1, int v2> int haha(T a) { return a * v1 * v2; } template <int v1, int v2> int haha(int a) { return a * v1 * v2; }