使用默认参数的模板参数推导行为

Template argument deduction behavior with default arguments

本文关键字:参数 默认      更新时间:2023-10-16

EDITED(原始问题只有int A,int B(:
当两个专门化之间比较的#参数相同时,模板参数推导会按预期工作,但当它们不同时(由于其中一个专门化中包含默认参数(,模板参数演绎会失败。

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

// 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<1,2,1,1>'

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> { /**/};

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

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