如何将模板函数指针作为值参数添加到地图中

How do I add a template function pointer as a value parameter to a map

本文关键字:参数 值参 添加 地图 指针 函数      更新时间:2023-10-16

我有一个工作框架,我正在使用一个映射来运行给定某个枚举的某个函数。这导致我有很多函数,所有函数都具有相同的签名,其中许多具有相同的代码。因此,我想提供一个模板函数指针作为映射中的值。这是工作设置:

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>}
}