Search code examples
c++variantc++17

Get the underlying type of a std::variant


Quick question:

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

My first guess was to use decltype() like this:

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

But the declared type for my vector is std::vector<std::variant<int, float>> not std::vector<int>.

Any idea of how I can achieve that ? :)


Solution

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

    Yes it definitely is

    Any idea of how I can achieve that ?

    Your try to achieve something very different than "get the underlying type used by a std::variant at runtime", as define std::vector type at runtime. This is very different issue and definitely not possible in this form as template instantiation happens at compile time. Closest solution would be to use std::variant<std::vector<int>, std::vector<float>> and use different vector based on runtime information from your variable v