2013-01-19 61 views
4

嘿所以我正在使用字符串作为键和成员函数指针作为值的映射。我似乎无法弄清楚如何添加到地图,这似乎并没有工作。C++字符串和成员函数指针的映射

#include <iostream> 
#include <map> 
using namespace std; 

typedef string(Test::*myFunc)(string); 
typedef map<string, myFunc> MyMap; 


class Test 
{ 
private: 
    MyMap myMap; 

public: 
    Test(void); 
    string TestFunc(string input); 
}; 





#include "Test.h" 

Test::Test(void) 
{ 
    myMap.insert("test", &TestFunc); 
    myMap["test"] = &TestFunc; 
} 

string Test::TestFunc(string input) 
{ 
} 
+2

猜测,但'&测试:: TestFunc '? – chris

+0

似乎修复参数中的一个错误,但我仍然得到一个错误插入 – ThingWings

+1

@Kosmo这是因为'插入'不工作的方式。 –

回答

9

value_type

myMap.insert(std::map<std::string, myFunc>::value_type("test", &Test::TestFunc)); 

std::map::insertstd::mapoperator[]

myMap["test"] = &Test::TestFunc; 

您不能使用成员函数指针没有对象。您可以使用成员函数指针与类型的对象Test

Test t; 
myFunc f = myMap["test"]; 
std::string s = (t.*f)("Hello, world!"); 

或用指针型Test

Test *p = new Test(); 
myFunc f = myMap["test"]; 
std::string s = (p->*f)("Hello, world!"); 

参见C++ FAQ - Pointers to member functions

+0

+1,虽然因为'std :: map :: value_type'是'pair '我喜欢插入'MyMap :: value_type(a,b)'而不是'std :: make_pair(a,b)'否则你得到'对'必须被转换为'对',并且转换不能被消除。 –

+0

@OlafDietsche +1美好的接吻! – dasblinkenlight

+0

我只是想知道是否将字符串文字传递给make_pair应该工作?毕竟,隐含的模板类型是char [5],而不是std :: string或somesuch。 –