2014-10-09 61 views
5

我想編寫一個模板類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 < > ; 
}; 

但如圖所示的代碼,這並不編譯由於錯誤。請幫助我瞭解什麼是錯的。

回答

5

您需要的模板關鍵字:

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> 
} 

Example

+1

哇!首先,我甚至沒有意識到爲什麼如果首先放置「T1」,反轉會發生。但是,這很有用,非常感謝! – 2014-10-09 12:19:44

1

你需要這樣的:

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

你失蹤中間的template關鍵字。