C++ 如何在映射中使用存储成员函数指针的Binder2nd对象?

C++ 如何在映射中使用存储成员函数指针的Binder2nd对象?,c++,stl,C++,Stl,我的问题类似于。我需要在映射中存储指向成员函数的指针。成员函数接受一个参数,该参数在构造映射时必须由特定值绑定。我该怎么做?贴图应具有binder2nd对象作为其值 例如: 我不知道如何声明此地图。下面是一个使用以下方法的示例: #包括“boost/function.hpp” #包括 #包括 #包括 结构Foo{ 空栏(整数x){ std::cout正如我从您对问题的评论中了解到的,您需要从字符串到枚举的映射,然后您想要调用具有枚举值的函数。 如果是这样的话,你为什么要把活页夹的事情弄得复杂呢

我的问题类似于。我需要在映射中存储指向成员函数的指针。成员函数接受一个参数,该参数在构造映射时必须由特定值绑定。我该怎么做?贴图应具有binder2nd对象作为其值

例如:


我不知道如何声明此地图。

下面是一个使用以下方法的示例:

#包括“boost/function.hpp”
#包括
#包括
#包括
结构Foo{
空栏(整数x){

std::cout正如我从您对问题的评论中了解到的,您需要从字符串到枚举的映射,然后您想要调用具有枚举值的函数。
如果是这样的话,你为什么要把活页夹的事情弄得复杂呢

您可以简单地执行以下操作:

// Initialize your map with appropriate string -> enum mappings.

地图的类型应为:

std::map<std::string, YourEnumType> yourMap;

就是这样,没有更多的活页夹;)

而不是
bind2nd
您可以使用
std::pair
手动完成。示例:

#include <map>
#include <functional>
#include <string>

enum { FOO, BAR };

class classA{
public:
    void Func(int){}
};

// define classAMemFn
typedef void (classA::*classAMemFn)(int);
// define element
typedef std::pair<classAMemFn, int> XElement;

typedef std::map<std::string, XElement> XMap;

void setup(XMap& xmap){
    xmap["FOO"]=std::make_pair(&classA::Func,FOO);
    xmap["BAR"]=std::make_pair(&classA::Func,BAR);
}

void Caller(XMap& xmap, const std::string& key, classA& obj){
    XMap::iterator it=xmap.find(key);
    if (it!=xmap.end()) {
        XElement e=it->second;
        (obj.*e.first)(e.second);
    }
}
#包括
#包括
#包括
枚举{FOO,BAR};
甲级{
公众:
void Func(int){}
};
//定义类amemfn
typedef void(classA::*classAMemFn)(int);
//定义元素
typedef std::pair XElement;
typedef std::map XMap;
无效设置(XMap和XMap){
xmap[“FOO”]=std::make_pair(&classA::Func,FOO);
xmap[“BAR”]=std::make_pair(&classA::Func,BAR);
}
void调用者(XMap和XMap,const std::string和key,classA和obj){
迭代器it=XMap.find(键);
如果(it!=xmap.end()){
XElement e=it->second;
(obj.*e.first)(e.second);
}
}
setup
函数将指针“绑定”到成员函数,并将参数“绑定”到字符串键


调用者
函数封装了在映射中查找配对并执行调用的繁琐工作。

您能否详细说明您想要实现什么?您想要存储这些东西的目的是什么?不清楚您为什么要使用映射。元素的关联是什么?换句话说,您想要在其中作为密钥映射?我有一个在枚举上带有开关大小写的func。枚举字符串作为命令行参数传递,我在映射中查找并调用绑定了字符串的枚举翻译的函数。我已经发布了一个答案,考虑到上面的细节。我不能使用boost。很抱歉,忘了提及。@Vivek:那么你必须编写自己的binder,因为
binder2nd
不能在
std::map
中使用,因为它不是默认可构造的。
callYourFunction(yourMap[yourStringFromInput]);
std::map<std::string, YourEnumType> yourMap;
SomeReturnType callYourFunction(YourEnumType e);
#include <map>
#include <functional>
#include <string>

enum { FOO, BAR };

class classA{
public:
    void Func(int){}
};

// define classAMemFn
typedef void (classA::*classAMemFn)(int);
// define element
typedef std::pair<classAMemFn, int> XElement;

typedef std::map<std::string, XElement> XMap;

void setup(XMap& xmap){
    xmap["FOO"]=std::make_pair(&classA::Func,FOO);
    xmap["BAR"]=std::make_pair(&classA::Func,BAR);
}

void Caller(XMap& xmap, const std::string& key, classA& obj){
    XMap::iterator it=xmap.find(key);
    if (it!=xmap.end()) {
        XElement e=it->second;
        (obj.*e.first)(e.second);
    }
}