反转元组参数

Invert tuple arguments

本文关键字:参数 元组      更新时间:2023-10-16

我想编写一个模板类InvTuple,它将type定义为按相反顺序排列的类参数元组。所以它应该像一样工作

InvTuple<T1, T2, T3, ...>::type   --->   tuple<..., T3, T2, T1>

我这样定义

template<class...T>
struct InvTuple;
template<class T1, class...T>
struct InvTuple < T1, T... >
{
    template<class... U>
    using doInvert = typename InvTuple<T...>::doInvert < U..., T1 > ;  
                     // <--- unrecognizable template declaration/definition, 
                     // syntax error : '<'
    using type = doInvert<>;
};
template<>
struct InvTuple <>
{
    template<class... U>
    using doInvert = tuple<U...>;
    using type = doInvert < > ;
};

但是,由于代码中显示的错误,这不会编译。请帮我弄清楚出了什么问题。

您需要模板关键字:

using doInvert = typename InvTuple<T...>::template doInvert < U..., T1 > ;

您还需要在同一行中切换U...T1才能正常工作:

#include <iostream>
#include <tuple>
#include <typeinfo>
using namespace std; // Don't try this at home
template<class...T>
struct InvTuple;
template<class T1, class...T>
struct InvTuple < T1, T... >
{
    template<class... U>
    using doInvert = typename InvTuple<T...>::template doInvert < T1, U... >;
    using type = doInvert<>;
};
template<>
struct InvTuple <>
{
    template<class... U>
    using doInvert = tuple<U...>;
    using type = doInvert < > ;
};
int main()
{
    InvTuple<int,char,bool> obj;
    InvTuple<int,char,bool>::type obj2;
    cout << typeid(obj).name() << endl; // InvTuple<int, char, bool>
    cout << typeid(obj2).name() << endl; // std::tuple<bool, char, int>
}

示例

您需要这个:

using doInvert = typename InvTuple<T...>::template doInvert < U..., T1 > ;

在中间缺少template关键字。