Search code examples
c++switch-statementc++17constexprvariant

Is it possible to get the index of a variant as a constexpr variable?


I have the following code (play with example). It checks what the underlying value of a variant is and receives this underlying value using get. As you can see the code gets quite repetitive.

#include <variant>
#include <string>
#include <iostream>
#include <vector>

int main()
{
    std::variant<int, double, std::string> v;
    // v holds a string
    v = "hi there!";

    switch(v.index()) {
        case 0: 
            {   // brackets to avoid cross initialization
                int i = std::get<int>(v);
                // handle int
            }    
            break;
        case 1: 
            {
                double d = std::get<double>(v);
                // handle double
            }
            break;
        case 2: 
            {
                std::string s = std::get<std::string>(v);
                // handle string
            }
            break;
    }
}

Question: Is there some way to get the index of a variant as a constexpr variable? I would like to do something like this:

// what I would like to do
// auto val_of_v = std::get<v.index()>(v);

// Error: template argument deduction/substitution failed
//        in 'constexpr' expansion of v<...>::index()

Related Post: Get index by type in std::variant.


Solution

  • Only if the variant is constexpr itself:

    constexpr std::variant<int, double> v{24};
    auto a = std::get<v.index()>(v);
    

    Otherwise the information can only be known at runtime.