我有一个对象接口和一个派生对象可能想要支持的开放式接口集合。
// 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)。