我有以下代码不能在 GCC 4.9 和 GCC 5.1 上编译。我似乎无法弄清楚为什么。抱歉,如果这是一个菜鸟问题,我是 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;
}
编译时出现如下错误
root@localhost# 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;
}
感谢任何帮助,或者如果已经有人问过这样的问题,请分享链接。
最佳答案
在这种情况下,您从 clang 获得的警告会更有帮助:
warning: dependent nested name specifier 'A<X>::' for friend class declaration is not supported
换句话说,A::C 是一个依赖类型,所以它不起作用(虽然我不知道在标准中的什么地方描述了这一点。
我怀疑实际上您只希望关系介于 A<T>
之间。和 B<T>
其中 T
是相同的(例如 A<int>
和 B<int>
但不是 A<char>
和 B<float>
)。如果是这种情况,您可以通过在友元声明中使用相同的模板参数来完成此操作
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
一个 friend 。
关于c++ - 模板嵌套私有(private)类作为 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882847/