Ami*_*rsh 5 c++ templates friend
给出以下代码:
class A;
struct B {
static void doIt(A* pa);
};
struct C {
static void doIt(A* pa);
};
class A {
int i = 9;
// below works but requires a line per each type
friend void B::doIt(A* pa);
friend void C::doIt(A* pa);
// the below however doesn't work
// template<typename T>
// friend void T::doIt(A* pa);
// (gcc error: member 'void T::doIt(A*)' declared as friend before type 'T' defined)
// (clang just ignores the above and the error is on accessing A::i in B and C)
};
void B::doIt(A* pa) {
cout << pa->i << endl;
}
void C::doIt(A* pa) {
cout << pa->i *2 << endl;
}
int main() {
A a;
B::doIt(&a);
C::doIt(&a);
}
Run Code Online (Sandbox Code Playgroud)
是否可以替换多个friend声明以允许所有void T::doIt(A* pa)方法访问私有成员A?
试图实例B和C上面A没有帮助.
我看不到直接的方法,但一种解决方法可以是声明一个具有多个静态方法的类(而不是具有一个静态方法的多个类),然后将此类声明为友元,例如:
...
struct D {
static void doItB(A* pa);
static void doItC(A* pa);
};
class A {
...
friend struct D;
...
};
void D::doItB(A* pa) {
cout << pa->i << endl;
}
...
D::doItB(&a);
D::doItC(&a);
...
Run Code Online (Sandbox Code Playgroud)