【问题标题】:How to call a template ctor of a template class?如何调用模板类的模板ctor?
【发布时间】:2017-05-05 15:37:54
【问题描述】:
template<typename T>
struct A
{
    template<typename U>
    A() {}

    template<typename U>
    static void f() {}
};

int main()
{
    A<int>::f<int>(); // ok
    auto a = A<int><double>(); // error C2062: type 'double' unexpected
}

问题在代码中不言而喻。

我的问题是:

如何调用模板类的模板ctor?

【问题讨论】:

  • 明显的绕过是A&lt;int&gt;::A&lt;double&gt;();,但这是非法的语法。因此,正如 Vittorio 在他的回答中提到的那样,如果没有某种包装器,这是不可能的。

标签: c++ templates syntax constructor type-deduction


【解决方案1】:

您不能直接调用类的构造函数。如果您不能从调用中推断出构造函数的模板参数,则无法调用该特定构造函数。

您可以做的是创建某种类型包装器,可用于零开销扣除:

template <typename T>
struct type_wrapper { };

template<typename T>
struct A
{
    template<typename U>
    A(type_wrapper<U>) {}
};

int main()
{
    auto a = A<int>(type_wrapper<double>{});
}

live example on wandbox

【讨论】:

    【解决方案2】:

    如何调用模板类的模板ctor?

    很遗憾,这是不可能的;您不能为构造函数模板显式指定模板参数。

    §17.5.2/5 Member templates [temp.mem]

    (强调我的)

    [ 注意:因为显式模板参数列表遵循 函数模板名称,并且因为转换成员函数 模板和 构造函数成员函数模板在没有调用的情况下调用 使用函数名,无法提供显式模板 这些函数模板的参数列表。 — 尾注 ]

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多