将非类型模板参数放入元组
get non-type template parameters into tuple
如何构造带有非类型模板参数的元组
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...);
| ^~~~
问题是,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...);
// ^^^^^^^^^^^^^^^^^^^^^
};
如何构造带有非类型模板参数的元组
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...);
| ^~~~
问题是,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...);
// ^^^^^^^^^^^^^^^^^^^^^
};