简体   繁体   中英

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

One way:

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

using value_t = decltype(as_variant(valid_types{}));

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

Using Boost.MP11, this is mp_rename :

using value_t = mp_rename< valid_types, std::variant >;

Godbolt link


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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM