我们有两个类模板:A 和 B,以及一个函数模板 f1()。像这样:
template< class T >
class A{};
template< class T >
class B
{
friend class A<T>; /* Expression 1 */
friend void f1( B<T> &b ); /* Expression 2 */
};
template< class T >
void f1( B<T> &b ) {}
int main()
{
A< int > a;
B< int > b;
f1( b );
return 0;
}
问题 1:表达式 1 使 A 与参数 T 的特化成为友元 B 与参数 T 的特化。但是如何使每个 A 的特化是 B 的特化的所有 friend 吗?
问题2:如何在类定义之外定义f1? 像这样的代码将产生一个错误:
undefined reference to `f1(B<int>&)'
问题 3:如何生成所有 f1()(谁可以接收 B 的所有特化作为参数) B 各专业的 friend ?
最佳答案
问题1:使用
template <typename U> friend class A;
而不是
friend class A<T>;
问题 2:表达式 2 的作用是将 friend 声明为一个采用 B 的普通函数,而不是函数模板的特化。要将friend声明为T的特化,您需要friend子句来查看f1的声明并添加<>
标记 f1 是一个特化函数,而不是一个重载的普通函数,所以
template< class T >
class B;
template< class T >
void f1( B<T> &b );
template< class T >
class B
{
friend void f1<>( B<T> &b );
};
template< class T >
void f1( B<T> &b ) {}
问题 3 的解决方案是两者的混合:
class B;
template< class T >
void f1( B<T> &b );
template< class T >
class B
{
template <typename U> friend void f1( B<U> &b );
};
关于c++ - 关于类模板的friend的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9686815/