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

标签 c++ reflection variant crtp algebraic-data-types

我怎样才能通过 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';
}

关于C++ 获取 std::variant 当前帮助的类型的 std::typeindex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58881846/

相关文章:

java - 通过注解对方法数组列表进行排序(Java 反射)

c# - 如果我有 PropertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?

java - PropertyUtils 性能

c++ - 从可以容纳 std::string 或 double 的变体返回 std::string

c++ - 根据是 C 还是 C++ 执行 header 中存在的不同代码

c++ - 在 OpenGL 中更新模板缓冲区时出现问题

c++ - 自定义 opengl 压缩纹理

c++ - 设备驱动程序: Windows ReadFile function timeout

c++ - 使用变体时,模板化的 child 不被接受为 parent

sorting - Delphi 字符串变体比较是否使用 loInvariantLocale?如何在本地启用 loUserLocale?