C++获取std::variant当前帮助的类型的std::typeindex



如何获取当前由c++中的变体帮助的类型的std::typeindex

假设我有一个变体:

using variant_t = std::variant<int, float, bool, double, std::string>;

我希望能够创建功能:

std::typeindex get_held_type(const variant_t& var);

这只是出于好奇,我知道这不是处理变体中数据的常用方法。

如果我向variant_t添加另一个类型,我不想更改任何其他代码。即类型需要是自注册的。

这是我迄今为止的尝试。我有点作弊,因为我使用映射而不是函数,并且必须构造一个对象才能在运行时注册类型。

#include <iostream>
#include <variant>
#include <string>
#include <vector>
#include <typeindex>
#include <map>
using variant_t = std::variant<int, float, bool, double, std::string>;
static constexpr size_t variant_t_size = std::variant_size<variant_t>();
static auto get_held_type = std::map<size_t, std::type_index>{};
//loop across all types in the variant
template<size_t N>
struct crtp : crtp<N - 1>{
//ctor
crtp(){
get_held_type[N] = std::type_index(typeid (std::get<N>(variant_t{})));
}
};
template<>
struct crtp<0>{
//ctor
crtp(){
get_held_type[0] = std::type_index(typeid (std::get<0>(variant_t{})));
}
};
static crtp<variant_t_size-1> registerTypes;
int main()
{
variant_t var = 3.141;
std::cout << get_held_type[var.index()].name() << std::endl;
}

但这在gcc中失败了,编译器错误:

/usr/include/c++/9/tuple:1674: error: no matching function for call to ‘std::type_index::type_index()’
1674 |         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
|                                                                      ^

std::visit在以统一的方式处理所有备选方案时非常方便。

std::visit([](auto& v) -> std::type_index { return typeid(v); }, var)

完整演示:

#include <iostream>
#include <variant>
#include <string>
#include <typeindex>
using variant_t = std::variant<int, float, bool, double, std::string>;
int main() {
variant_t var = 3.141;
std::cout << std::visit([](auto& v) -> std::type_index { return typeid(v); }, var).name() << 'n';
}

最新更新