简体   繁体   English

不允许非类型参数的部分模板专业化

[英]Partial template specialization of non type argument not allowed

The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. 以下代码不起作用,它给出错误消息:“ struct foo的模板参数太少”,我不明白为什么。 To me it seems like the code should be valid. 在我看来,该代码应该是有效的。 I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it. 我发现从CPP参考片段这里参见“参数列表”,第4段这或许可以解释为什么它不工作,但我不明白。

template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };

int main()
{
    foo<1> f;
}

It's allowed. 允许 But your template takes 3 parameters. 但是您的模板需要3个参数。 Specializing it doesn't magically turn it into a 1 parameter template. 专门化它不会神奇地将其变成1参数模板。

You can make the other parameter have default arguments, however: 您可以使其他参数具有默认参数,但是:

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

Note that the primary template takes 3 template parameters. 请注意,主模板具有3个模板参数。 Then you have to specify all of them. 然后,您必须指定所有这些。 eg 例如

foo<1, 0, 0> f; // the partial specification is used

It's not how template specialization works. 模板专业化不是这样工作的。 You have* to specify all arguments. 您必须*指定所有参数。
*(Except when you have default arguments (see @StoryTeller's answer), or when C++17 argument deduction kicks in, but both don't apply here.) *(除非您具有默认参数 (请参见@StoryTeller的答案),或者当C ++ 17参数推演生效时,但两者均不适用于此处。)

Here's a small demo: 这是一个小演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM