具有默认参数的模板参数推导行为

时间:2019-10-31 20:05:57

标签: c++ templates

编辑(原始问题只有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;
}

错误:“ Foo <1、1、1、1>类”的模板实例化不明确

1 个答案:

答案 0 :(得分:1)

access-control-allow-origin: *

具有默认参数:

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

具有(有效):

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

template <int B> class Foo <1, B> { /*..*/ }; Foo<1, 1>匹配时,您对Foo<A, 1>含糊不清,但都不是更专业。

Foo<1, B>

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

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