一个类A有方法func1,有时候我们希望这个func1只在某个特定的类B中被调用。以下是一种实现方法:
template<class T>
class FriendAccess
...{
friend typename T; // error if write class keyword instead of typename here, but okay if typename is ignored, why?
FriendAccess();
};
class B; // forward declaration
class A
...{
public:
void fun1(FriendAccess<B> fb) const
...{
cout << "invoke legally" << endl;
};
};
class B
...{
public:
void invoke(A* pa) const
...{
if (pa)
pa->fun1(FriendAccess<B>());
}
};因为FriendAccess的ctor被声明为private,所以其只能在template的type param中被构造,A的func1中指定了这个type param只能是B,也就将A::func1的调用范围限定在了B内部。主要原理还是利用了模板和友元的结合。
不过这里比较诡异的是FriendAccess中如果我写friend class T,编译的时候(测试用的是vc2005)居然还是说FriendAccess的ctor无法访问,必须写成typename。然而如果我再写一个特化的FriendAccess<B>版本,其中直接写friend class B,就ok了,诡异!哪位能分析下?
本文介绍了一种使用C++模板和友元机制来限制类A的方法func1仅能在特定类B中被调用的方法。通过定义一个带有模板参数的FriendAccess类,并将其构造函数设为私有,以此确保只有类B能够构造FriendAccess实例并调用A的func1方法。
1643

被折叠的 条评论
为什么被折叠?



