vendredi 15 novembre 2019

C++ Get std::typeindex of type currently help by std::variant

How can I get the get the std::typeindex of the type currently help by a variant in c++?

Say I have a variant:

using variant_t = std::variant<int, float, bool, double, std::string>;

I want to be able to create the function:

std::typeindex get_held_type(const variant_t& var);

This is just for curiosity, I know that this is not the usual way to handle data in a variant.

Here is my attempt so far. I cheat a bit, as I use a map instead of a function, and an object has to be constructed in order to register the types at run time.

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

using variant_t = std::variant<int, float, bool, double, std::string>;
static constexpr size_t variant_t_size = std::variant_size<variant_t>();
static auto get_held_type = std::map<size_t, std::type_index>{};

//loop across all types in the variant
template<size_t N>
struct crtp : crtp<N - 1>{
    //ctor
    crtp(){
        get_held_type[N] = std::type_index(typeid (std::get<N>(variant_t{})));
    }
};

template<>
struct crtp<0>{
    //ctor
    crtp(){
        get_held_type[0] = std::type_index(typeid (std::get<0>(variant_t{})));
    }
};

static crtp<variant_t_size-1> registerTypes;

int main()
{
    variant_t var = 3.141;
    std::cout << get_held_type[var.index()].name() << std::endl;

}

But this fails with gcc with the compiler error:

/usr/include/c++/9/tuple:1674: error: no matching function for call to ‘std::type_index::type_index()’
 1674 |         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
      |                                                                      ^




Aucun commentaire:

Enregistrer un commentaire