假设我有:
class A {};
template <typename T> class B {};
template <typename T> class C {};
class D : public C<B<A>> {
//friend ... ??
};
有没有办法为class D
构建一个朋友声明,使得A
类型的实例是D
的朋友。 B<A>
类型的一个实例是D
的朋友。 C<B<A>>
类型的一个实例是D
的朋友。等等,对于一些任意数量的嵌套模板类型,自动,而不必在D
中使用多个朋友声明手动指定?
编辑:要添加一些上下文,所需的应用程序是使用“链接”CRTP接口的样式与公共函数,在实现类中调用受保护的“覆盖”函数,额外的“朋友”声明有点难看,但不是太繁重我猜测这种风格的合成界面的长度。
#include <iostream>
template <typename T>
struct static_base {
T& self() { return static_cast<T&>(*this); }
T const& self() const { return static_cast<T const&>(*this); }
};
template <typename Derived>
class InterfaceBase : public static_base<Derived> {};
template <typename Derived>
class Interface1 : public Derived {
public:
void foo() { this->self().foo_(); }
};
template <typename Derived>
class Interface2 : public Derived {
public:
void bar() { this->self().bar_(); }
};
template <typename Derived>
class Interface3 : public Derived {
public:
void baz() { this->self().baz_(); }
};
class Impl : public Interface3<Interface2<Interface1<InterfaceBase<Impl>>>> {
friend Interface3<Interface2<Interface1<InterfaceBase<Impl>>>>;
friend Interface2<Interface1<InterfaceBase<Impl>>>;
friend Interface1<InterfaceBase<Impl>>;
protected:
void foo_() { std::cout << "foo" << "\n"; }
void bar_() { std::cout << "bar" << "\n"; }
void baz_() { std::cout << "baz" << "\n"; }
};
int main() {
auto impl = Impl();
impl.foo();
impl.bar();
impl.baz();
}
你害怕,你必须单独为每个班级的朋友。你不能继承友谊,所以我认为不可能用一个朋友的声明来做这件事。