Behzad
Behzad

Reputation: 151

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>;
}

Upvotes: 1

Views: 1604

Answers (2)

KamilCuk
KamilCuk

Reputation: 140960

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);

Upvotes: 5

max66
max66

Reputation: 66200

Not sure, but I suppose you're looking for something as follows

#include <variant>
#include <iostream>

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

template <std::size_t I>
auto typeReturn (myVariant const & v)
 {
        if constexpr ( I == 0 ) return std::get<double>(v);
   else if constexpr ( I == 1 ) return std::get<int>(v);
   else if constexpr ( I == 2 ) return std::get<std::string>(v);
   else                         return std::get<int>(v);
}

int main ()
 {
   myVariant b = 1.2;

   double c = typeReturn<0u>(b);

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

Observe that you need use if constexpr and pass the index as template parameter.

Upvotes: 1

Related Questions