【问题标题】:Number of template arguments in templated constructor模板化构造函数中的模板参数数量
【发布时间】:2014-09-16 10:17:04
【问题描述】:

对于一个(可能是非模板化的)类,我可以有一个模板化的构造函数:

struct A {
    template<class T> A(T const& arg) {}
}

模板参数的数量是否受可推导的参数数量的限制?如果是这样,相关的标准报价是什么?

例如,如果构造函数是

template<class T1, class T2> A(T2 const& arg) {}

这个调用会导致编译错误

A<int>(double()); // creation of a temporary

或者我将如何调用构造函数?这也失败了:

A::A<int>(double()); // creation of a temporary

【问题讨论】:

  • “我将如何调用构造函数” - 不是。

标签: c++ templates c++11 language-lawyer c++14


【解决方案1】:

标准中有一条说明,你不能在构造函数中使用显式模板参数:

[ 注意:因为显式模板参数列表遵循函数模板名称, 并且因为调用了转换成员函数模板和构造函数成员函数模板 如果不使用函数名,就无法为这些提供显式模板参数列表 功能模板。 ——尾注]

来源:14.5.2 Member templates 来自 N3337 草案。

当然,你可以拥有比构造函数参数更多的构造函数模板参数——只要它们可以从构造函数参数中推导出来:

例子:

struct A {
    template<class T, int N> A(T (&arg)[N]) {}
};

【讨论】:

  • 只要它们可以从构造函数参数或(其他/默认)模板参数中推导出来。
【解决方案2】:

您无法使用 template-argument-list 语法传递类型的事实并不一定意味着您根本无法传递模板化构造函数的类型列表:

template <typename...>
struct _ {};

struct A
{
    template <class T1, class T2, class T3>
    A(_<T1, T2, T3>) {}
};

int main()
{
    A a{_<int, double, char>{}};
}

LIVE DEMO

【讨论】:

  • 非常感谢老兄的分享。
  • 是否有语言支持为模板化构造函数指定 template-argument-list 的建议?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多