Search code examples
c++c++17variantstd-variant

define a function to return specified type of std::variant c++


I am almost new to using c++17 rules. My question is straightforward; how can I access the std::variant types in the same order I defined them? Something like the following code that I know is not working!

#include <variant>
#include <iostream>

using myVariant = std::variant<double, int, std::string>;

template<typename T>
T   typeReturn(int i);

int main(void)
{
    myVariant b = 1.2;

    double c = typeReturn(1)(b);

    std::cout << c << std::endl;

    return 0;
}

template<typename T>
T typeReturn(int i)
{
    if (i == 0) return std::get<double>;
    else if (i == 1) return std::get<int>;
    else if (i == 2) return std::get<std::string>;
    else return std::get<int>;
}

Solution

  • how can I access the std::variant types in the same order I defined them?

    No need to write it yourself - std::get already does that. Just:

    double c = std::get<0>(b);