如何对(任意)POD C++结构施加词典顺序?

ein*_*ica 0 c++ reflection lexicographic lexicographic-ordering

我有一些POD struct foo; 假设是的struct foo { int x; unsigned y; }.我希望能够struct foo使用词典顺序进行比较- 当然是按照他们的字段顺序进行比较.也就是说,我希望所有的运营商<,==>等为工作struct foo

我可以用一些通用的方式做到这一点,而没有用任何反射巫术装饰我的结构定义- 而且没有拼写出所有那些操作符定义?或者是否有能力做到这一点太依赖"语言反思"的期望?

krz*_*zaq 5

你可以用C++ 1z做到这一点.基于这个答案,我准备了以下概念证明:

struct anything {
    template<class T> operator T()const;
};

namespace details {
template<class T, class Is, class=void>
struct can_construct_with_N:std::false_type {};

template<class T, std::size_t...Is>
struct can_construct_with_N<T, std::index_sequence<Is...>,
        std::void_t< decltype(T{(void(Is),anything{})...}) >>:
                                                             std::true_type
{};
}

template<class T, std::size_t N>
using can_construct_with_N=details::can_construct_with_N<T, std::make_index_sequence<N>>;

namespace details {
template<std::size_t Min, std::size_t Range, template<std::size_t N>class target>
struct maximize: std::conditional_t<
    maximize<Min, Range/2, target>{} == (Min+Range/2)-1,
    maximize<Min+Range/2, (Range+1)/2, target>,
    maximize<Min, Range/2, target>
>{};

template<std::size_t Min, template<std::size_t N>class target>
struct maximize<Min, 1, target>: std::conditional_t<
    target<Min>{},
    std::integral_constant<std::size_t,Min>,
    std::integral_constant<std::size_t,Min-1>
>{};

template<std::size_t Min, template<std::size_t N>class target>
struct maximize<Min, 0, target>:
    std::integral_constant<std::size_t,Min-1>
{};

template<class T>
struct construct_searcher {
    template<std::size_t N>
    using result = ::can_construct_with_N<T, N>;
};

template<class T, std::size_t Cap=4>
using construct_arity = details::maximize< 0, Cap, details::construct_searcher<T>::template result >;

template<typename T>
constexpr auto tie_as_tuple_impl(std::integral_constant<size_t, 1>, T&& t){
    auto&& [a] = t;
    return std::tie(a);
}

template<typename T>
constexpr auto tie_as_tuple_impl(std::integral_constant<size_t, 2>, T&& t){
    auto&& [a,b] = t;
    return std::tie(a,b);
}

template<typename T>
constexpr auto tie_as_tuple_impl(std::integral_constant<size_t, 3>, T&& t){
    auto&& [a,b,c] = t;
    return std::tie(a,b,c);
}

template<size_t S, typename T>
constexpr auto tie_as_tuple(T&& t){
    return tie_as_tuple_impl(std::integral_constant<size_t, S>{}, std::forward<T>(t));
}

}

template<typename T>
constexpr auto tie_as_tuple(T&& t){
    constexpr size_t S = details::construct_arity<std::decay_t<T>>::value;
    return details::tie_as_tuple<S>(std::forward<T>(t));
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以tie_as_tuple按照您要求的方式创建一个元组,其中包含您已经定义的所有运算符.

演示

请注意,我必须准备几个重载tie_as_tuple_impl,一个用于结构中每个元素的数量,但是对于结构元素的数量线性扩展.


在C++ 14中magic_get,可以允许类似的解决方案,但它有其警告,请参阅此处以获取更多信息.