0

我正在尝试在 GUI 内实现通信系统。出于可维护性的原因,我想避免访问者模式。同样,如果 else 语句不可维护,则制作 dynamic_cast。我最接近的方法是使用 Scott Meyers 的 More Effective 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);
}

其中 dispatch 是一种自动检查传入命令的 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 可能吗?

4

1 回答 1

0

您可能会执行以下操作:

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);
于 2020-05-20T12:59:48.690 回答