【问题标题】:Partial template specialization of non type argument not allowed不允许非类型参数的部分模板特化
【发布时间】:2017-11-14 11:03:30
【问题描述】:

以下代码不起作用,它给出了一个错误,提示“struct foo 的模板参数太少”,我不明白为什么。对我来说,代码似乎应该是有效的。我在“参数列表”部分的第 4 段中从 CPP 参考 here 中找到了一个 sn-p,这可能解释了它为什么不起作用但我不明白。

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

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

【问题讨论】:

    标签: c++ templates metaprogramming template-meta-programming


    【解决方案1】:

    这是允许的。但是您的模板需要 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;
    }
    

    【讨论】:

    • 我现在可以将其称为 foo 而不是 foo 的专业化的想法不是吗?
    • @BananyaDev - 不。专业化是关于控制一组特定参数的行为。它不会改变你需要传递多少参数。
    • @BananyaDev - 但是可以为参数添加默认参数。
    【解决方案2】:

    这不是模板专业化的工作方式。您必须* 指定所有参数。
    *(除非您有 默认参数(请参阅@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
    }
    

    【讨论】:

      【解决方案3】:

      请注意,主模板采用 3 个模板参数。然后你必须指定所有这些。例如

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-02-02
        • 1970-01-01
        相关资源
        最近更新 更多