【问题标题】:unpack a parameter pack of pairs into an array and a tuple将成对的参数包解压成数组和元组
【发布时间】:2021-10-07 01:03:55
【问题描述】:

所以我有一个成对列表,其中第一个成员是一个常量整数,第二个是一个类型,有没有办法将它解压缩到第一个成员的数组和第二个成员的元组中?

struct MA {}
struct MB {}
struct MC {}
template <int I, class T> struct MyPair{};

我怎样才能使模板元函数具有这两个成员:

MyStruct<1, MA, 2, MB, 3, MC> {
     std::array<int, 3> arr = {1, 2, 3};
     using Tuple = std::tuple<MA, MB, MC>;
};

【问题讨论】:

    标签: c++ templates c++17 variadic-templates parameter-pack


    【解决方案1】:

    只需定义两个辅助元函数即可获取IT

    template<class> struct GetFirst;
    template<int I, class T> struct GetFirst<MyPair<I, T>> {
        static constexpr int value = I;
    };
    
    template<class> struct GetSecond;
    template<int I, class T> struct GetSecond<MyPair<I, T>> {
        using type = T;
    };
    
    template<class... MyPairs>
    struct MyStruct {
        std::array<int, sizeof...(MyPairs)> arr{GetFirst<MyPairs>::value...};
        using Tuple = std::tuple<typename GetSecond<MyPairs>::type...>;
    };
    
    //////////////////////////////////////////////////
    
    using S = MyStruct<MyPair<1, MA>, MyPair<2, MB>, MyPair<3, MC>>;
    static_assert(std::is_same_v<S::Tuple, std::tuple<MA, MB, MC>>);
    assert((S{}.arr == std::array{1, 2, 3}));
    

    你不能在可变参数模板中混合类型和非类型参数,所以不可能有

    MyStruct<1, MA, 2, MB, 3, MC, ...>
    

    没有将(int, Type) 包装成一个类型。


    正如 JeJo 在下面的评论中提到的,这两个元功能可以合并为一个:

    template<class> struct MyPairTraits;
    template<int I, class T> struct MyPairTraits<MyPair<I, T>> {
        static constexpr int i = I;
        using Type = T;
    };
    

    【讨论】:

    • 谢谢,在这种情况下需要前向声明template&lt;class&gt; struct GetFirst;吗?
    • @fluter - 这是主要的模板。在主要声明可用之前,我们无法专门化。如果你删除它,专业化就会变得不正确。
    • 对,它不是前向声明而是主模板,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多