【发布时间】:2013-02-07 02:41:42
【问题描述】:
我有一个对象接口和一个派生对象可能想要支持的开放式接口集合。
// An object
class IObject
{
getAttribute() = 0
}
// A mutable object
class IMutable
{
setAttribute() = 0
}
// A lockable object
class ILockable
{
lock() = 0
}
// A certifiable object
class ICertifiable
{
setCertification() = 0
getCertification() = 0
}
一些派生对象可能如下所示:
class Object1 : public IObject, public IMutable, public ILockable {}
class Object2 : public IObject, public ILockable, public ICertifiable {}
class Object3 : public IObject {}
这是我的问题:有没有一种方法可以编写只采用这些接口的某些组合的函数?例如:
void doSomething(magic_interface_combiner<IObject, IMutable, ILockable> object);
doSomething( Object1() ) // OK, all interfaces are available.
doSomething( Object2() ) // Compilation Failure, missing IMutable.
doSomething( Object3() ) // Compilation Failure, missing IMutable and ILockable.
我发现最接近的是 boost::mpl::inherit。我取得了一些有限的成功,但它并没有完全满足我的需要。
例如:
class Object1 : public boost::mpl::inherit<IObject, IMutable, ILockable>::type
class Object2 : public boost::mpl::inherit<IObject, ILockable, ICertifiable>::type
class Object3 : public IObject
void doSomething(boost::mpl::inherit<IObject, ILockable>::type object);
doSomething( Object1() ) // Fails even though Object1 derives from IObject and ILockable.
doSomething( Object2() ) // Fails even though Object2 derives from IObject and ILockable.
我认为类似于 boost::mpl::inherit 的东西可能会生成一个具有所提供类型的所有可能排列的继承树。
我也很好奇解决这个问题的其他方法。理想情况下,编译时检查而不是运行时检查(即没有 dynamic_cast)。
【问题讨论】:
-
您是指 AND 组合还是 OR 组合?
-
如果我错了请纠正我,但是你的抽象函数不需要标记
virtual以及=0吗? -
我认为使用模板是错误的答案?
-
在新的 C++11 标准中,有很多新的type traits,例如
std::is_base_of。可以与std::enable_if结合使用。 -
为什么需要
doSomething才能同时通过这么多接口?您的问题可能暗示存在设计缺陷。
标签: c++ inheritance interface multiple-inheritance boost-mpl