nya*_*108 1 c++ overriding multiple-inheritance
我有以下代码使用多重继承.目的是在派生类中使用两个接口作为一个接口:
struct InterfaceA
{
virtual void register_stuff();
virtual void on_state_changed( const State state ) = 0;
};
struct InterfaceB
{
virtual void register_stuff();
virtual void on_state_changed( const State state ) = 0;
};
struct Derived : InterfaceA, InterfaceB
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
void on_state_changed( const State state ) override
{
// how can I know who is responding?
}
};
Run Code Online (Sandbox Code Playgroud)
注册接口将导致异步调用on_state_changed.是否有可能辨别哪个接口正在调用它?
您必须在中间添加一个图层才能消除歧义.这是一个小型实用程序,可以即时创建它们:
template<class Inteface>
struct disambiguate : Interface {
void on_state_changed( const State state ) override final {
on_state_changed(state, this);
}
virtual void on_state_changed( const State &state, disambiguate* ) = 0;
};
Run Code Online (Sandbox Code Playgroud)
就是这样.然后,根据此实用程序定义您的类是一个问题:
struct Derived : disambiguate<InterfaceA>, disambiguate<InterfaceB>
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
void on_state_changed( const State &state, disambiguate<InterfaceA>* ) override
{
// Called for A
}
void on_state_changed( const State &state, disambiguate<InterfaceB>* ) override
{
// Called for B
}
};
Run Code Online (Sandbox Code Playgroud)
我已经使用了另一个参数和重载来使这个模板化,但是技术本身也可以通过编写类并使用新名称调用虚函数来完成.关键是使原始虚拟调用(通过接口指针)到达调用消除歧义的函数的短thunk.
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |