我正在尝试将
vector
s 的 variant
可变地转换为 tuple
s 的 vector
(即我想将以下代码分解为可变参数模板 std::variant<Ts...>
)。
std::vector<std::variant<float, int>> vector_of_variants;
vector_of_variants.emplace_back(1);
vector_of_variants.emplace_back(2.f);
std::tuple<std::vector<float>, std::vector<int>> result;
for (auto& el : vector_of_variants)
{
auto index = el.index();
std::get<index>(result).pushback(std::get<index>(el)); // error: index is runtime value
}
但是,
std::get<index>(result).pushback(std::get<index>(el));
行显然行不通,我需要用一些 std::visit
之类的行为替换它(即生成行 tuple_size
次并在运行时委托)。
符合人体工程学的方法是什么?
假设您已保证变体中的相应索引和
result
匹配,类似下面的内容应该适用于天真的实现。可能不是最好的表现:
[&]<std::size_t... Is>(std::index_sequence<Is...>){
(index == Is && std::get<Is>(result).push_back(std::get<Is>(el)), ...);
}(std::make_index_sequence<std::tuple_size_v<decltype(result)>>{});