c++映射的异构函数



我想创建一个c++脚本,使用map执行异构函数,并将输入/输出存储在map中。为了处理异质性,我想使用any类型。但是,这会产生问题,因为函数指针不能转换any类型中的其他类型。

下面是一个不工作的最小示例,但说明了我想要做的:

#include <string.h>
#include <stdio.h>
#include <iostream>
#include <map>
#include <any>
using namespace std;
string funct1(int a, int b)
{  
int c= a+b;
string name = to_string(c);
return name ;
}
float funct2(int a, int b)
{
// float b2
float c=a-b;
return c ;
}
int main(void) 
{ 
cout << "START" << endl;
std::map<std::string, std::any> ListObjIn; // 
std::map<std::string, std::any> ListObjOut; // 
typedef std::any (*FnPtr)(std::any, int);  
std::map<std::string, FnPtr> ListCommand; // 
// 
ListObjIn["a1"] = 1;
ListObjIn["a2"] = 1.5;
ListCommand["do1"]= funct1;
ListCommand["do2"]= funct2;
// ListObjOut["res1"]= ListCommand["do1"]( std::any_cast<int>(ListObjIn["a1"]), 2); 
ListObjOut["res1"]= ListCommand["do1"]( ListObjIn["a1"], 2);
cout << "RESULT 1=" << std::any_cast<string>(ListObjOut["res1"]) << endl;
ListObjOut["res2"]= ListCommand["do2"]( ListObjIn["a2"], 2);
cout << "RESULT 2=" << std::any_cast<string>(ListObjOut["res2"]) << endl;
cout << "END" << endl;   
return(0); 
} 

我得到以下错误:

g++ -std=c++17 ./test.cpp 
./test.cpp: In function ‘int main()’:
./test.cpp:34:24: error: invalid conversion from ‘std::__cxx11::string (*)(int, int) {aka std::__cxx11::basic_string<char> (*)(int, int)}’ to ‘std::map<std::__cxx11::basic_string<char>, std::any (*)(std::any, int)>::mapped_type {aka std::any (*)(std::any, int)}’ [-fpermissive]
ListCommand["do1"]= funct1;
^~~~~~
./test.cpp:35:24: error: invalid conversion from ‘float (*)(int, int)’ to ‘std::map<std::__cxx11::basic_string<char>, std::any (*)(std::any, int)>::mapped_type {aka std::any (*)(std::any, int)}’ [-fpermissive]
ListCommand["do2"]= funct2;
^~~~~~

我试图将函数的输入和输出类型(即stringfloat)更改为any,但这会在其他地方产生转换问题。

所以有可能有一些非常接近我原来的例子,保持类型输入/输出和函数映射的异质性?还是应该考虑变通?

您可能应该使用std::any:

泛化返回类型https://godbolt.org/z/G1EhqY

最新更新