使用参数包自动执行dynamic_cast检查



我正在尝试在GUI内部实现通信系统。出于可维护性的原因,我想避免使用访问者模式。同样,如果 else 语句dynamic_cast不可维护。我最接近的是使用Scott Meyers的更有效C++中的表实现多个调度。

到目前为止,我有:

SubmitCommand(BaseCommand* pCommand)
{
m_Distpatcher->Dispatch<DerivedCommand1>(pCommand);
m_Distpatcher->Dispatch<DerivedCommand2>(pCommand);
m_Distpatcher->Dispatch<DerivedCommand3>(pCommand);
}

我想去的地方是:

SubmitCommand(BaseCommand* pCommand)
{
m_Distpatcher->Dispatch<DerivedCommand1,
DerivedCommand2,
DerivedCommand3>(pCommand);
}

其中调度是检查传入命令dynamic_cast结果的自动方法。

template<typename K>
void Dispatch(ICommand* pCommand)
{
auto pConcreteCommand = dynamic_cast<K*>(pCommand);
if (pConcreteCommand)
{
//call Recieve on the interface of the owner class
m_pInstance->Recieve(pConcreteCommand);
}
}

在这种情况下,将在编译时检查特定模块,以确保它对模板中的每个参数都有一个函数。代码块 2 可能吗?

你可以做这样的事情:

template <typename ... Ts>
void Distpatcher::Dispatch(BaseCommand* pCommand)
{
(DispatchUnique<Ts>(pCommand), ...); // C++17
}

所以

m_Distpatcher->Dispatch<DerivedCommand1,
DerivedCommand2,
DerivedCommand3>(pCommand);

将等同于

m_Distpatcher->DispatchUnique<DerivedCommand1>(pCommand);
m_Distpatcher->DispatchUnique<DerivedCommand2>(pCommand);
m_Distpatcher->DispatchUnique<DerivedCommand3>(pCommand);

最新更新