是否可以在for循环中通过std::tuple_cat组合元组,更改之前计算的元组?
我想按如下方式使用该函数:
std::tuple<int> data;
for(int i = 0; i < max; i++)
{
/* ... some function which changes the value of data ... */
auto temp = std::tuple_cat(temp, data); // Add the new data to the previous tuple
}
它在逻辑上是不可编译的(在初始化之前无法使用 temp(。我该如何解决这个问题?
按照您在for
循环中的逻辑,元组的大小预计会发生变化。
这不可能。由于元组的大小应为编译时常量,因此不能使用与不同大小的元组相同的变量。
你可以做的是这样的:
template <typename F, std::size_t ... Is>
auto tuple_generator_seq(F&& f, std::index_sequence<Is...>)
{
const decltype(f(0u)) arr[] = {f(Is)...}; // To force order of evaluation
return std::make_tuple(arr[Is]...);
}
template <std::size_t N, typename F>
auto tuple_generator(F&& f)
{
return tuple_generator_seq(f, std::make_index_sequence<N>());
}
int main()
{
auto data = 42;
auto t = tuple_generator<5>([&](int ){ return ++data; });
std::apply([](auto... e){ ((std::cout << e << " "), ...); }, t);
}
演示