如何简化由make_variant_over生成的类型

How to simplify type generated by make_variant_over

本文关键字:类型 over variant 何简化 make      更新时间:2023-10-16

Boost变体具有称为make_variant_over的函数,该函数采用MPL序列(例如list<A, B, C>),并从这些类型中产生一个变体。

但是,如果仔细看,生成的类型从来都不是简单的variant<A, B, C>

例如,在此代码中,

#include<boost/variant.hpp>
int main(){
    using List = boost::mpl::list<double, int>;
    using Variant = boost::make_variant_over<List>::type;
}

Variantboost::variant<boost::detail::variant::over_sequence<boost::mpl::list<double, int, mpl_::na, ...> >>

看起来它可以与boost::variant<double, int>互换使用,但不是相同的类型。充其量在阅读编译器错误时会产生混乱,而在最坏的情况下,它可能很难实现依赖于参数的确切类型的某些功能。

是否有一种方法可以强制生产的变体类型中的简化?

使用 boost::mpl::fold得到它。由于无法实例化空模板变体,因此必须小心递归。

可以做到,但是我们可能没有做任何支持,因为boost::variant<T1, T2,...>可能仍在boost::variant<...variant::over_sequence<T1, T2,...>>中实现。

真正的力量可以是可以使用简化的类型结构使变体类型独特。

namespace detail{
template <typename TList, typename T> struct ExtendTList;
template<typename T>
struct ExtendTList<boost::variant<void>, T>{
  using type = boost::variant<T>;
};
template<typename T, typename... Ts>
struct ExtendTList<boost::variant<Ts...>, T>{
  using type = boost::variant<Ts..., T>;
};
}
template<class Seq>
using make_simple_variant_over = typename boost::mpl::fold<
    typename boost::mpl::fold<
        Seq,
        boost::mpl::set<>, 
        boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>
    >::type,
    boost::variant<void>, 
    detail::ExtendTList<boost::mpl::_1, boost::mpl::_2>
>;
...
using variant_type = make_simple_variant_over<boost::mpl::vector<int, int, long>>::type;

variant_type现在正好是boost::variant<int, long>

(并且不是boost::variant<boost::detail::variant::over_sequence<boost::mpl::list<int, long, mpl_::na, ...> >>也不是boost::variant<boost::detail::variant::over_sequence<boost::mpl::list<int, int, long, mpl_::na, ...> >>