如何将模板函数指针作为值参数添加到地图中
How do I add a template function pointer as a value parameter to a map
我有一个工作框架,我正在使用一个映射来运行给定某个枚举的某个函数。这导致我有很多函数,所有函数都具有相同的签名,其中许多具有相同的代码。因此,我想提供一个模板函数指针作为映射中的值。这是工作设置:
QMap <ENUM,OutputWidget *(MainWindow::*)()>func_map;
OutputWidget *handle_first();
OutputWidget *handle_second();
func_map{{FIRST,&MainWindow::handle_first},{SECOND,&MainWindow::handle_second}};
OutputWidget *output1 = (this->*func_map[FIRST])();
OutputWidget *output2 = (this->*func_map[SECOND])();
我也希望能够更改func_map来处理此签名,但我一直无法弄清楚如何:
template <typename INPUTTYPE,typename OUTPUTTYPE> OUTPUTTYPE *handle_all();
我尝试将此模板添加到地图中;
func_map{{FIRST,&MainWindow::handle_first},SECOND,&MainWindow::handle_second},{THIRD,&MainWindow::handle_all<FirstInputWidget,ThirdOutputWidget>}}
但这导致了以下错误:
../TemplateTest/mainwindow.cpp: In constructor ‘MainWindow::MainWindow(QWidget*)’:../TemplateTest/mainwindow.cpp:9:14: error: no matching function for call to ‘QMap<ENUM, OutputWidget* (MainWindow::*)()>::QMap(<brace-enclosed initializer list>)’
}
能够添加此模板将减少我的大量代码。如果有人对如何实现这一点有任何想法,我将不胜感激。
谢谢
这里没有真正的问题,你只需要获取函数模板实例的地址:
func_map{
{FIRST, &MainWindow::handle_all<FirstType, OutputWidget>},
{SECOND, &MainWindow::handle_all<SecondType, OutputWidget>}
}
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 如何将不同模板参数值但相同类型的值放入这种类型的变量中?C++
- 如何使用 C++ 解析具有参数名称和参数值的 XML
- 解析参数值 - 字符串和链接值(类型字符串的链接值)与(特定类型的)变量
- 如何将非可变参数值传递给 fmt::format?
- 用默认参数值和空参数列表区分构造函数
- 是否可以在尾随返回类型语法中直接使用参数值(不是其类型,而是值本身)
- 如何创建可变参数模板函数来移动参数值并处理左值和右值
- C++17 使用选定的构造函数在堆栈中构造数组(每个数组条目的构造函数参数值相同)
- 什么是包裹着色器参数值的类的好设计模式
- 是默认模板模板参数值推导的上下文
- 使用多个参数值调用模板函数
- 在解析分配给默认参数值的重载函数时,要考虑哪组函数
- 默认参数值错误 [Visual C++ 2008 中的错误?
- 根据输入参数值调用不同的基类构造函数
- 正在获取第n个可变参数值(不是类型)
- 传递将默认参数值作为模板参数的函数
- 参数值的自动模板函数专用化
- 临时参数值何时超出范围
- 为什么我们可以检测 SFINAE 中 operator() 的默认参数值的存在,而不是自由函数和 PMF 的默认参数值