【问题标题】:Template argument deduction behavior with default arguments带有默认参数的模板参数推导行为
【发布时间】:2020-02-27 05:39:33
【问题描述】:

已编辑(原始问题只有 int A,int B):
当特化之间比较的#arguments 相同时,模板参数推导按预期工作,但当它们不同时失败(由于包括包含在其中一种特化中的默认参数)。

例如:为什么模板参数推导在一种情况下与另一种情况下失败,有人可以指出任何解释这一点的资源/标准吗?

// Example program
#include <iostream>

template <int A, int B, int C, int D=1>
class Foo;

template <int A, int B, int C>
class Foo <A, B, C>
{
public:
    int a;

    Foo()
    {
        a = 0;
    }
};

template <int D>               // Fails compilation
class Foo <1, 1, 1, D>         // Fails compilation
//template <>                  // works, prints a = 1
//class Foo <1, 1, 1>          // works, prints a = 1
{
public:
    int a;

    Foo()
    {
        a = 1;
    }
};


int main()
{
    Foo <1, 1, 1, 1> f;
    std::cout << "a = "<< f.a << std::endl;
}

错误:‘class Foo’的模版实例化不明确

【问题讨论】:

    标签: c++ templates


    【解决方案1】:
    template <int A>
    class Foo <A> {/*..*/};
    

    带有默认参数:

    template <int A>
    class Foo <A, 1> {/*..*/};
    

    有(有效):

    template <int B>
    class Foo <1, B> { /*..*/ };
    

    Foo&lt;1, 1&gt; 有歧义,Foo&lt;A, 1&gt;Foo&lt;1, B&gt; 都匹配,但都没有更专业。

    template <> class Foo <1> { /**/};
    

    template <> class Foo <1, 1> { /**/};
    

    并且比之前的两个专业都更加专业。

    【讨论】:

    • 我想在这个更简单的例子中,你说的很有道理,所以让我编辑我的问题
    • 所以在编辑后的问题中 Foo 与 Foo 匹配得更好,而不是 Foo -但编译器仍然抱怨。
    • Foo&lt;1, 1, 1, D&gt; 并不比Foo&lt;A, B, C, 1&gt;专业。通俗地说,“T1 比 T2 更专业”是指“T1 接受的(子集)类型少于 T2”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2012-11-18
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2018-07-04
    相关资源
    最近更新 更多