模板专用类之间的构造函数重载

constructor overloading between template specialized classes

本文关键字:构造函数 重载 之间 专用      更新时间:2023-10-16

在下面的代码中,我有一个类模板及其专用化。

template<size_t U>
struct Foo
{
    Foo(double(&u)[U]) : u{ u } {}
    double(&u)[U];
};
template<>
struct Foo<1>
{
    double &u;
    bool specialized = true;
    Foo(double &u) : u{ u } {}
};

如果我尝试使用推导的模板参数创建一个实例,则构造函数参数将仅与泛型Foo对象匹配。

double s[7] = { 1, 2, 3, 4, 5, 6, 7 };
Foo f(s); // will deduce s is of type Foo<7>
double t = 5.;
Foo g(t); // no instance matches the argument list!
Foo<1> g(t); // I must explicitly tell it I'm using the specialization

当然,如果专用类具有相同的构造函数参数,并且我做了类似Foo g(t) t 是类型 double[1] 的事情,则该实例将是专用类型。

那么,在这种情况下,为什么也没有解析专用构造函数(或其他构造函数集的一部分(呢?

隐式生成的演绎指南仅考虑主模板,但您可以自行添加演绎指南:

Foo(double &u) -> Foo<1>;

演示

另请注意

double t[1] = {5.};
Foo g(t); // deduce Foo<1>, but fails as specialization doesn't have compatible constructor