如何简化 make_variant_over 生成的类型

How to simplify type generated by make_variant_over

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, ...> >>