首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异构功能的C++映射

异构功能的C++映射
EN

Stack Overflow用户
提问于 2021-03-12 01:30:52
回答 1查看 72关注 0票数 0

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

以下是一个不起作用的最小示例,但说明了我想要做的事情:

代码语言:javascript
复制
#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); 
} 

我得到以下错误:

代码语言:javascript
复制
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,但这在其他地方造成了转换问题。

因此,有可能有一些非常接近我的原始示例,保持类型输入/输出和函数映射的异构性?还是应该考虑变通一下?如果是,是哪一个?

EN

回答 1

Stack Overflow用户

发布于 2021-03-12 01:45:10

您可能应该使用std::any:泛化返回类型:

https://godbolt.org/z/G1EhqY

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66587557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档