2015-06-17 46 views
3

我有下面的代码不能在GCC 4.9和GCC 5.1上编译。我似乎无法弄清楚为什么。对不起,如果这是一个noob问题,我是一种新的C++模板。作为朋友的模板嵌套私人类

template<class T>class A 
{ 
    template<class X>friend class B; 
    struct C {}; 
}; 

template<class X>class B 
{ 
    template<class T>friend struct A<T>::C; 
}; 

int main() 
{ 
    A<int> a; 
    B<float> b; 
} 

编译时我收到以下错误

[email protected]# g++-49 templatefriend.cpp 
templatefriend.cpp: In instantiation of âclass B<float>â: 
templatefriend.cpp:38:9: required from here 
templatefriend.cpp:27:9: error: âstruct A<T>::Câ is private 
    struct C {}; 
    ^
templatefriend.cpp:31:1: error: within this context 
{ 
^ 

在那里,如果我删除

class A 
{ 
    friend class B; 
    class C{}; 
}; 

class B 
{ 
    friend class A::C; 
}; 

int main() 
{ 
    A a; 
    B b; 
} 

任何帮助表示赞赏模板,或者如果这样的问题已经编译没有问题被问到,请分享链接。

+0

对不起我的错,错的评论,整流 –

+0

'C'的模板,因为它是'A' –

+0

@RyanHaining我想我必须学习很多有关模板中:P –

回答

2

你铛获得这种情况下的警告是一个比较有用的:

warning: dependent nested name specifier 'A<X>::' for friend class declaration is not supported 

换句话说,A :: C是一个依赖型,所以它不工作(虽然我不T OFF-手知道在哪里的标准,这是描述。

我怀疑的是,在现实中,你只需要的关系是A<T>B<T>之间,其中T是相同的(例如A<int>B<int>但不A<char>B<float> )如果是这种情况,你可以acco通过使用相同的模板参数在friend声明

template <typename T> class B; 

template<class T> 
class A { 
    friend class B<T>; // B of the same templated type is my friend 
    struct C {}; 
}; 

template<class T> 
class B { 
    friend struct A<T>::C; // A::C of the same templated type is my friend 
}; 

另一种方法是有template <typename> class A;B里面,然后也会使A::C朋友mplish这一点。

+1

你说得对铛,只是cjeck铿锵++ 3.5,并得到了错误。但我不想要依赖的朋友。意思A :: C和B 也可以成为朋友! –