2012-07-24 60 views
13

我今天在C++11中使用using關鍵字時出現問題。我決定現在使用另一種方法(在下面的例子中添加爲註釋)。您可以將X作爲矩陣,將Y視爲混合矩陣,其目標是訪問Y中的矩陣類型X。我們採用了另一種更強大的方法,並且定義了一個本身帶有兩個模板參數的別名,而不是typedef ing X<B,A>X<A,B>C++ 11`using`關鍵字:特殊化模板參數的模板別名

template <class A, class B> 
struct X 
{ 
    using Left = A; 
    using Right = B; 
    template <class T1, class T2> 
    using Sibling = X<T1, T2>; 
    // using Reversed = X<B, A>; // What I really want and use now. :-) 
}; 

template <class A> 
struct Y 
{ 
    using Left = typename A::Left; 
    using Right = typename A::Right; 
    using AReverse = typename A::Sibling<Right, Left>; // Gives a compiler error 
    // using AReverse2 = typename A::Reversed; // Works, of course. 
}; 

using Z = X<int,double>::Sibling<double,int>; // Works 

我試圖編譯上面g++-4.7 -std=c++11 -c的代碼,它讓我看到以下錯誤消息:

t.cpp:16:9: error: expected nested-name-specifier before ‘AReverse’ 
t.cpp:16:9: error: using-declaration for non-member at class scope 
t.cpp:16:18: error: expected ‘;’ before ‘=’ token 
t.cpp:16:18: error: expected unqualified-id before ‘=’ token 

我不明白爲什麼一個在所有得到錯誤信息或者我怎麼能解決這個問題。有人能向我解釋什麼是問題嗎?

非常感謝!

回答

9

您需要刪除typename,並使用::template代替:

using AReverse = A::template Sibling<Right, Left>; 

在這種情況下(Sibling)的標識符的::權是不是一個類型,它是一個模板,這就是爲什麼這消歧是需要而不是typename

+3

這是不正確。此處還需要'typename'關鍵字,因爲'A ::兄弟姐妹<...>'是一個依賴範圍的類型名稱。 – 2013-07-14 06:57:27

8

這裏鏘這樣說:

<stdin>:16:32: error: use 'template' keyword to treat 'Sibling' as a dependent template name 
    using AReverse = typename A::Sibling<Right, Left>; // Gives a compiler error 
          ^
           template