c – 如何在容器中存储具有不同签名的功能对象?

c – 如何在容器中存储具有不同签名的功能对象?,第1张

概述所以想象我们有2个函数(void:(void))和(std :: string:(int,std :: string)),我们还有10个函数.所有(或其中一些)采用不同的参数类型,并可以返回不同的类型.我们想将它们存储在std :: map中,因此我们得到一个这样的API: //Having a functions like:int hello_world(std::string name, c 所以想象我们有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;}//andvoID 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 – 如何在容器中存储具有不同签名的功能对象?全部内容,希望文章能够帮你解决c – 如何在容器中存储具有不同签名的功能对象?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1220674.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存