c – 如何在容器中存储具有不同签名的功能对象?
发布时间:2020-12-16 10:30:29 所属栏目:百科 来源:网络整理
导读:所以想象我们有2个函数(void:(void))和(std :: string:(int,std :: string)),我们还有10个函数.所有(或其中一些)采用不同的参数类型,并可以返回不同的类型.我们想将它们存储在std :: map中,因此我们得到一个这样的API: //Having a functions like:int hel
所以想象我们有2个函数(void:(void))和(std :: string:(int,std :: string)),我们还有10个函数.所有(或其中一些)采用不同的参数类型,并可以返回不同的类型.我们想将它们存储在std :: map中,因此我们得到一个这样的API:
//Having a functions like: int hello_world(std::string name,const int & number ) { name += "!"; std::cout << "Hello," << name << std::endl; return number; } //and void i_do_shadowed_stuff() { return; } //We want to be capable to create a map (or some type with similar API) that would hold our functional objects. like so: myMap.insert(std::pair<std::string,fun_object>("my_method_hello",hello_world) ) myMap.insert(std::pair<std::string,fun_object>("my_void_method",i_do_shadowed_stuff) ) //And we could call tham with params if needed: int a = myMap["my_method_hello"]("Tim",25); myMap["my_void_method"]; 我想知道如何将许多不同的功能放入同一个容器中.具体来说,如何使用Boost在C 03中完成此操作. API应独立于实际的函数类型(具有int a = myMap [“my_method_hello”](“Tim”,25); not int a = myMap< int,(std :: string,int)> [“my_method_hello “](”蒂姆“,25岁);). 解决方法#include <functional> #include <iostream> #include <string> #include <map> class api { // maps containing the different function pointers typedef void(*voidfuncptr)(); typedef int(*stringcrintptr)(std::string,const int&); std::map<std::string,voidfuncptr> voida; std::map<std::string,stringcrintptr> stringcrint; public: // api temp class // given an api and a name,it converts to a function pointer // depending on parameters used class apitemp { const std::string n; const api* p; public: apitemp(const std::string& name,const api* parent) : n(name),p(parent) {} operator voidfuncptr() { return p->voida.find(n)->second; } operator stringcrintptr() { return p->stringcrint.find(n)->second; } }; // insertion of new functions into appropriate maps void insert(const std::string& name,voidfuncptr ptr) { voida[name]=ptr; } void insert(const std::string& name,stringcrintptr ptr) { stringcrint[name]=ptr; } // operator[] for the name gets halfway to the right function apitemp operator[](std::string n) const { return apitemp(n,this); } }; 用法: api myMap; int hello_world(std::string name," << name << std::endl; return number; } int main() { myMap.insert("my_method_hello",&hello_world ); int a = myMap["my_method_hello"]("Tim",25); } http://ideone.com/SXAPu不是很漂亮.更好的建议是不要做任何事情,就像你正在尝试做的那样. 请注意,这要求具有相同参数的所有函数返回相同的类型. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 返回LINQ结果时何时调用ToList的经验法则
- c# – BinaryReader读取4个字节,但没有得到预期的结果
- 红宝石 – 从Sinatra内调用Sinatra
- C++对象数组(详解版)
- 南沙政府应急系统之GIS一张图(arcgis api for flex)讲解(
- c:如何在构造函数中初始化std :: pair的成员
- reactjs – 如何使用react-router-redux routeActions?
- pgcli通过SSH本地转发连接远程服务器上的PostgreSQL DB
- Oracle SQL语言基础及环境准备_超越OCP精通Oracle视频教程培
- logback.xml配置如何按天输出日志文件