获取 std::variant 的基础类型

Get the underlying type of a std::variant

快速提问:

是否可以在运行时获取 std::variant 使用的基础类型?

我的第一个猜测是像这样使用 decltype()

    std::variant<int, float> v;
    v = 12;
    std::vector<decltype(v)> vec;

但是我的向量声明的类型是 std::vector<std::variant<int, float>> 而不是 std::vector<int>

知道如何实现吗? :)

Is it possible to get the underlying type used by a std::variant at runtime ?

是的,绝对是

Any idea of how I can achieve that ?

您尝试实现与 "get the underlying type used by a std::variant at runtime" 截然不同的东西,如在运行时定义 std::vector 类型。这是一个非常不同的问题,并且在这种形式下绝对不可能,因为模板实例化发生在编译时。最接近的解决方案是使用 std::variant<std::vector<int>, std::vector<float>> 并根据来自变量 v

的运行时信息使用不同的向量