如何将通过模板传递的所有std::size_t
参数相加为一个定义数组大小的std::size_t
值。
template<typename T, std::size_t... N>
class Example {
std::array<T, N + ...> data; // std::array<T, sum of all N...>
};
你几乎已经拥有了。你需要为此使用一个fold表达式,这是相同的语法,只是用()
包围。这会给你
template<typename T, std::size_t... N>
struct Example {
std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
};
在这个例子中,您会得到一个错误,告诉数组成员的大小是参数和的大小。
template<typename T, std::size_t... N>
struct Example {
std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
};
template <typename T>
struct get_type;
int main()
{
Example<int, 1, 2, 3> ex;
get_type<decltype(ex.data)>{};
}
错误:
main.cpp: In function 'int main()':
main.cpp:27:33: error: invalid use of incomplete type 'struct get_type<std::array<int, 6> >'
27 | get_type<decltype(ex.data)>{};
| ^
main.cpp:22:8: note: declaration of 'struct get_type<std::array<int, 6> >'
22 | struct get_type; ^
| ^~~~~~~~ |
// here you see 1 + 2 + 3 == 6 --------+
实例