将非类型模板参数放入元组

use*_*729 1 c++ templates variadic-templates c++11 c++17

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

son*_*yao 9

问题是,默认成员初始值设定项(C++11 起)支持大括号和等号初始值设定项,但不支持括号初始值设定项。您可以将代码更改为:

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

或者

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

并借助类模板参数推导(C++17 起):

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