c++ - 使用参数包自动化 dynamic_cast 检查
问题描述
我正在尝试在 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 可能吗?
解决方案
您可能会执行以下操作:
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);
推荐阅读
- java - 使用spring的Json body整数验证
- sql-server - 如何减慢所有 SQL 查询?
- excel - 解压缩文件时出现空白excel电子表格
- asp.net - 找不到“Newtonsoft.Json”的版本
- javascript - 没有 jsx 的反应,我可以使用模板字符串而不是 createElement 吗?
- python - 获取与已删除项目相关的 app_id 的任何方式(API)
- pentaho - Pentaho PDI (Kettle/spoon) 文本文件元数据注入
- phpunit - 使用 webDriver 进行覆盖的 Codeception C3 配置
- reactjs - 太多的 React 上下文提供程序
- android - handler.postDelayed() 没有停止