不允许非类型参数的部分模板特化
Partial template specialization of non type argument not allowed
下面的代码不起作用,它给出了一个错误 "Too few template arguments for struct foo",我不明白为什么。在我看来,代码应该是有效的。我在 "The argument list" 部分的第 4 段中找到了 CPP 参考资料 here 中的一个片段,它可能解释了为什么它不起作用,但我不明白。
template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };
int main()
{
foo<1> f;
}
这是允许的。但是您的模板需要 3 个参数。专门化它并不能神奇地将它变成一个 1 参数模板。
您可以使其他参数具有默认参数,但是:
template<int a, int b = 0, int c = 0> struct foo { char _[1] ; };
template<int a> struct foo<a, 0, 0> { char _[10] ;};
int main() {
static_assert(sizeof(foo<1>) > sizeof(foo<1, 1, 1>), "");
return 0;
}
请注意,主模板采用 3 个模板参数。然后你必须指定所有这些。例如
foo<1, 0, 0> f; // the partial specification is used
这不是模板专业化的工作方式。您必须*指定所有参数。
*(除非您有 默认参数 (请参阅@StoryTeller 的回答),或者当 C++17 参数推导开始时,但两者均不适用于此处。)
这是一个小演示:
#include <iostream>
template<int a, int b, int c> struct foo { void bar() {std::cout << "1\n";} };
template<int a> struct foo<a, 0, 0> { void bar() {std::cout << "2\n";} };
int main()
{
foo<1, 2, 3> a;
foo<4, 0, 0> b;
a.bar(); // prints 1
b.bar(); // prints 2
}
下面的代码不起作用,它给出了一个错误 "Too few template arguments for struct foo",我不明白为什么。在我看来,代码应该是有效的。我在 "The argument list" 部分的第 4 段中找到了 CPP 参考资料 here 中的一个片段,它可能解释了为什么它不起作用,但我不明白。
template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };
int main()
{
foo<1> f;
}
这是允许的。但是您的模板需要 3 个参数。专门化它并不能神奇地将它变成一个 1 参数模板。
您可以使其他参数具有默认参数,但是:
template<int a, int b = 0, int c = 0> struct foo { char _[1] ; };
template<int a> struct foo<a, 0, 0> { char _[10] ;};
int main() {
static_assert(sizeof(foo<1>) > sizeof(foo<1, 1, 1>), "");
return 0;
}
请注意,主模板采用 3 个模板参数。然后你必须指定所有这些。例如
foo<1, 0, 0> f; // the partial specification is used
这不是模板专业化的工作方式。您必须*指定所有参数。
*(除非您有 默认参数 (请参阅@StoryTeller 的回答),或者当 C++17 参数推导开始时,但两者均不适用于此处。)
这是一个小演示:
#include <iostream>
template<int a, int b, int c> struct foo { void bar() {std::cout << "1\n";} };
template<int a> struct foo<a, 0, 0> { void bar() {std::cout << "2\n";} };
int main()
{
foo<1, 2, 3> a;
foo<4, 0, 0> b;
a.bar(); // prints 1
b.bar(); // prints 2
}