在我当前的项目中,我需要能够提供基于模板的多重继承(Mixin 模式)and有两个可以一起交互的类(具有镜像多重继承树)(即一个类在同一继承级别使用另一个类的方法)。
长话短说,我似乎找不到一种优雅的方式来构建它。下面是一个简化的测试用例(您可以直接运行并编辑它here http://ideone.com/6JY2ut).
是否有一种模式或技巧可以让我拥有与注释行类似的内容,同时保持任何子类相对简单?
显然,嵌套的Thing
类需要从另一个提供必要接口方法的类继承。然而,任何修复继承问题(CRTP ...)的尝试似乎总是导致我遇到递归继承或不完整的基类型问题......
class Base {
public:
class Thing {
public:
Thing(Base& b) : _b(b) {};
Thing& operator+= (const Thing p) { _b.add(*this, p); return *this; };
int k;
protected:
Base& _b;
};
void add(Thing &d, const Thing s) { d.k += s.k; }
};
template <class... Interfaces>
class Extensible : virtual public Base, virtual public Interfaces... {
class Thing : virtual public Base::Thing, virtual public Interfaces::Thing... {
};
};
class SomeInterface : Base {
void multiply(Thing &d, const Thing s) { d.k *= s.k; }
class Thing : public Base::Thing {
Thing& operator*= (const Thing p) {
//_b.multiply(*this, p); return *this; // <-- won't work of course
};
};
};
int main() {
Extensible<SomeInterface> a;
return 0;
}
这是选项之一:http://ideone.com/KhLyfj http://ideone.com/KhLyfj(我只是告诉基类它的子类是什么_b
正确的类型)。但在某些情况下它不起作用。您可以尝试将模板从Thing
/add
直接到Base
.
class Base {
public:
template<typename Outer>
class Thing {
public:
Thing(Base& b) : _b(b) {};
Thing& operator+= (const Thing p) { _b.add(*this, p); return *this; };
int k;
protected:
Outer& _b;
};
template<typename Outer>
void add(Thing<Outer> &d, const Thing<Outer> s) { d.k += s.k; }
};
template <class... Interfaces>
class Extensible : virtual public Base, virtual public Interfaces... {
class Thing : virtual public Base::Thing<Base>, virtual public Interfaces::template Thing<Base>... {
};
};
class SomeInterface : Base {
void multiply(Thing<SomeInterface> &d, const Thing<SomeInterface> s) { d.k *= s.k; }
class Thing : public Base::Thing<SomeInterface> {
Thing& operator*= (const Thing p) {
_b.multiply(*this, p); return *this; // <-- will work of course
};
};
};
int main() {
Extensible<SomeInterface> a;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)