namespace { template <class T> struct A { template <class BB> void foo(BB const& b) { b.bar(); } }; } // end anonymous namespace template <class T> class B { template <class> friend struct A; protected: void bar() const {} }; int main() { A<int> a; a.foo(B<int>{}); }
> A和B都是模板.然后Intel icc 18:错误#308:函数“B< T> :: bar [with T = int]”无法访问,gcc 7.2:没有错误,clang 5.0:没有错误
> A是模板而B是模板:Intel icc 18:没有错误,gcc 7.2:错误:’void B< T> :: bar()const [with T = int]’在此上下文中受到保护,第5条:没有错误
> A是模板而B不是:Intel icc 18:错误#308,gcc 7.2:错误,clang 5:没有错误
> A和B都不是模板:Intel icc 18:没有错误,clang 5:没有错误
> A和B都不是模板(如4中所示),但A和B的位置交换:Intel icc 18:错误#308,clang 5:错误:’bar’是’B’的受保护成员
> A和B都是模板(如1.),clang 5:错误
有关案例6,请参阅编译器资源管理器中的示例:https://godbolt.org/g/6Zdr3c和https://godbolt.org/g/BRqf78.
那么,正确的行为是什么?哪个编译器正确?
解决方法
未命名的命名空间(7.3.1.1:1)的定义指出,未命名的命名空间定义等同于定义具有转换单元唯一名称的命名命名空间,然后使用using指令导入该命名空间.
这将使A的声明在全球范围内可获得,并根据第11.3:9段
A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration.
因此参数化的类A是B的朋友,并且应该能够访问B :: bar
在案例5中存在差异.据我所知,friend声明在封闭范围内声明了一个新的参数化类A,它与未命名的命名空间中的类A不同.