【问题标题】:using tr2::direct_bases get nth element of result使用 tr2::direct_bases 获取结果的第 n 个元素
【发布时间】:2013-03-01 13:03:00
【问题描述】:
struct T1 {};
struct T2: T1 {};

typedef tr2::direct_bases<T2>::type NEW_TYPE ;

应该将我的类似的东西返回到基本类型。我怎样才能得到第n个元素 这个 __reflection_typelist<...>。我为反射列表搜索类似 tuple_element 的东西。

【问题讨论】:

    标签: c++ c++11 c++-tr2


    【解决方案1】:

    您可以使用这个简单的元函数将类型列表变成std::tuple

    #include <tr2/type_traits>
    #include <tuple>
    
    template<typename T>
    struct dbc_as_tuple { };
    
    template<typename... Ts>
    struct dbc_as_tuple<std::tr2::__reflection_typelist<Ts...>>
    {
        typedef std::tuple<Ts...> type;
    };
    

    此时,您可以像通常使用元组一样使用它。例如,您可以通过以下方式检索类型列表的元素:

    struct A {};
    struct B {};
    struct C : A, B {};
    
    int main()
    {
        using namespace std;
    
        using direct_base_classes = dbc_as_tuple<tr2::direct_bases<C>::type>::type;
    
        using first = tuple_element<0, direct_base_classes>::type;
        using second = tuple_element<1, direct_base_classes>::type;
    
        static_assert(is_same<first, A>::value, "Error!");   // Will not fire
        static_assert(is_same<second, B>::value, "Error!");  // Will not fire
    }
    

    【讨论】:

    【解决方案2】:

    自己写?

    template <typename R, unsigned int N> struct get;
    
    template <typename T, typename ...Args, unsigned int N>
    struct get<std::tr2::__reflection_typelist<T, Args...>, N>
    {
        typedef typename get<std::tr2::__reflection_typelist<Args...>, N - 1>::type type;
    };
    
    template <typename T, typename ...Args>
    struct get<std::tr2::__reflection_typelist<T, Args...>, 0>
    {
        typedef T type;
    };
    

    甚至使用first/next:

    template <typename R, unsigned int N>
    struct get
    {
        typedef typename get<typename R::next::type, N - 1>::type type;
    };
    
    template <typename R>
    struct get<R, 0>
    {
        typedef typename R::first::type type;
    };
    

    在这一点上,我想说source code 是最好的文档。

    【讨论】:

    • +1 表示first / next 示例。我会添加static_assert( !R::empty::value, "Cannot get element of empty typelist" ) 或使用std::conditional&lt;R::empty::value, void, blahblah&gt;
    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 2014-12-27
    • 2018-08-07
    • 2010-10-16
    • 2016-12-14
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多