2013-01-19 2 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::map를 참조 operator[]

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

을 위해 당신은 객체없이 멤버 함수에 대한 포인터를 사용할 수 없습니다. 당신은

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

또는 포인터 Test

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 '이기 때문에'std :: make_pair (a, b)'가 아닌'MyMap :: value_type (a, b)'를 삽입하는 편이 더 좋습니다. ''쌍을 '쌍 '으로 변환해야하고 그 변환을 생략 할 수 없습니다. –

+0

@OlafDietsche +1 좋은 캐치! – dasblinkenlight

+0

make_pair에 문자열 리터럴을 전달하는 것이 효과가 있는지 궁금합니다. 결국, 묵시적인 템플릿 유형은 char [5]가 아니라 std :: string 또는 somesuch입니다. –

관련 문제