Reputation: 331
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 >;
Upvotes: 4
Views: 2472
Reputation: 275240
This is the shortest, most concise way I know of to do this:
template < class ... Types > struct type_list {
template<template<class...>class Z>
using apply_to = Z<Types...>;
};
using value_t = value_types::apply_to<std::variant>;
you can get fancier. For example:
template<class T, template<class...>class Z>
struct transcribe_parameters;
template<class T, template<class...>class Z>
using transcribe_parameters_t = typename
transcribe_parameters<T,Z>::type;
template<template<class...>class Zin, class...Ts, template<class...>class Zout>
struct transcribe_parameters<Zin<Ts...>, Zout> {
using type=Zout<Ts...>;
};
which gives you:
using value_t = transcribe_parameters_t<value_types, std::variant>;
but, having that be a built-in feature of type_list
doesn't seem unreasonable.
Upvotes: 1
Reputation: 25277
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 >;
Upvotes: 4
Reputation: 25277
Using Boost.MP11, this is mp_rename
:
using value_t = mp_rename< valid_types, std::variant >;
Alternatively, mp_apply
is the same operation with the operands flipped, if you find it more readable:
using value_t = mp_apply< std::variant, valid_types >;
Upvotes: 2
Reputation: 256
If you're fine with augmenting your type_list structure:
template <class ... Types> struct type_list {
using variant_type = std::variant< Types...>;
};
If you want it as a separate funcion:
template <class T> struct type_list_variant;
template <class... Types> struct type_list_variant<type_list<Types...>> {
using type = std::variant<Types...>;
};
template <class T>
using type_list_variant_t = typename type_list_variant<T>::type;
Upvotes: 0
Reputation: 136208
One way:
template<class... Types>
std::variant<Types...> as_variant(type_list<Types...>);
using value_t = decltype(as_variant(valid_types{}));
Upvotes: 6