2014-10-09 8 views
5

Chcę napisać szablon klasy InvTuple, który definiuje type jako krotka argumentów klasowych w kolejności odwrotnej. Tak to powinno działać jakArgumenty odwróconej tupii

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

I tak jak zdefiniowano go

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

Ale to nie skompilować z powodu błędu, jak pokazano w kodzie. Pomóż mi zrozumieć, co jest nie tak.

Odpowiedz

5

Musisz słowa kluczowego Szablon:

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

i trzeba także przełączyć U... i T1 w tej samej linii, aby mieć tę pracę odpowiednio:

#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

Wow! Najpierw nie zdawałem sobie nawet sprawy, dlaczego inwersja ma miejsce, gdy 'T1' jest postawione jako pierwsze. Ale to działa, wielkie dzięki! –

1

Trzeba to:

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

Byłaś brakuje template słowa kluczowego w środku.