1.解决方案:您可以将变量转换为元组,然后使用 C++17 std::apply:
#include <variant>
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
using namespace std;
template <typename... Types>
struct ToTuple;
template <typename... Types>
struct ToTuple<variant<Types...>>
{
using type = tuple<Types...>;
};
struct TypeA {};
struct TypeB {};
struct TypeC {};
using TaskVariant = std::variant<TypeA, TypeB, TypeC>;
int main()
{
vector<TaskVariant> vec;
apply([&vec](auto&&... args) {(vec.push_back(args), ...); }, ToTuple<TaskVariant>::type{});
}
编辑:
2.解决方案:使用make_index_sequence、variant_alternative_t和variant_size_v(所有 C++17)(感谢@sd指出variant_alternative_t,但我已经修改了使用make_index_sequence而不是递归的示例):
#include <variant>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct TypeA {};
struct TypeB {};
struct TypeC {};
using TaskVariant = std::variant<TypeA, TypeB, TypeC>;
template <size_t... Idx>
void fill_vec(vector<TaskVariant>& vec, index_sequence<Idx...> idx)
{
(vec.push_back(variant_alternative_t<Idx, TaskVariant>{}), ...);
}
int main()
{
vector<TaskVariant> vec;
fill_vec(vec, make_index_sequence<variant_size_v<TaskVariant>>{});
}