2012-07-24 122 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