C++ 将嵌套的基模板类实例声明为派生类的友元
假设我有:C++ 将嵌套的基模板类实例声明为派生类的友元,c++,templates,inheritance,friend,C++,Templates,Inheritance,Friend,假设我有: class A {}; template <typename T> class B {}; template <typename T> class C {}; class D : public C<B<A>> { //friend ... ?? }; 恐怕每个班你都得单独交朋友。你不能继承友谊,所以我认为用一个朋友声明不可能做到这一点。看起来你在写混音。如果使用多重继承,可能会更干净。但这并不能消除多个好友声明。 #in
class A {};
template <typename T> class B {};
template <typename T> class C {};
class D : public C<B<A>> {
//friend ... ??
};
恐怕每个班你都得单独交朋友。你不能继承友谊,所以我认为用一个朋友声明不可能做到这一点。看起来你在写混音。如果使用多重继承,可能会更干净。但这并不能消除多个好友声明。
#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();
}