Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predefined type list passed to a std::variant

Is there any way to create a pre-defined type list, and use those types in a std::variant in c++ 17? Here is what I'm trying to do, it compiles, but doesn't work as I was hoping:

template < class ... Types > struct type_list {};
using valid_types = type_list< int16_t, int32_t, int64_t, double, std::string >;
using value_t = std::variant< valid_types >;
like image 588
David Massat Avatar asked Dec 18 '22 18:12

David Massat


2 Answers

One way:

template<class... Types> 
std::variant<Types...> as_variant(type_list<Types...>);

using value_t = decltype(as_variant(valid_types{}));
like image 176
Maxim Egorushkin Avatar answered Dec 29 '22 02:12

Maxim Egorushkin


This can be done by having type_list send Types into the metafunction (std::variant):

template < class ... Types > struct type_list {
    template < template < class... > class MFn >
    using apply = MFn< Types... >;
};
// Optional. For nicer calling syntax:
template < template < class... > class MFn, class TypeList >
using apply = typename TypeList::template apply< MFn >;

using valid_types = type_list< int16_t, int32_t, int64_t, double, std::string >;
using value_t = apply< std::variant, valid_types >;

Godbolt link

like image 25
Justin Avatar answered Dec 29 '22 04:12

Justin