【问题标题】:get non-type template parameters into tuple将非类型模板参数放入元组
【发布时间】:2021-03-27 19:26:44
【问题描述】:

如何构造非类型模板参数的元组

template <auto... args>
void func()
{
  std::tuple<decltype(args)...> t(args...);
  cout << get<3>(t) << endl;
}

template <auto... args>
struct ZZ
{
  std::tuple<decltype(args)...> t(args...);
};


int main()
{
   func<1,2,3,4>();
   ZZ<1,2,3> z;
}

虽然它适用于func,但它不适用于结构并导致编译错误(gcc trunk)

vs.cc:102:35: error: ‘args’ is not a type
  102 |   std::tuple<decltype(args)...> t(args...);
      |                                   ^~~~

【问题讨论】:

  • ZZ::t 尝试声明一个函数。

标签: c++ c++11 templates c++17 variadic-templates


【解决方案1】:

问题是,default member initializer(C++11 起)支持大括号和等号初始化程序,但不支持括号初始化程序。您可以将代码更改为:

template <auto... args>
struct ZZ
{
  std::tuple<decltype(args)...> t{args...};
  //                             ^       ^
};

或者

template <auto... args>
struct ZZ
{
  std::tuple<decltype(args)...> t = std::tuple<decltype(args)...>(args...);
  //                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};

在class template argument deduction(C++17 起)的帮助下:

template <auto... args>
struct ZZ
{
  std::tuple<decltype(args)...> t = std::tuple(args...);
  //                              ^^^^^^^^^^^^^^^^^^^^^
};

【讨论】:

  • 演绎指南使 decltype 变得多余,不是吗?
  • @Yakk-AdamNevraumont 是的。
猜你喜欢
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2011-08-06
  • 1970-01-01
相关资源
最近更新 更多