2012-01-20 8 views
0
class MyObject{ 
public: 
    void testFunctionMap(){ 
     std::unordered_map<std::string, std::function<void()> > functionMap; 
     std::pair<std::string, std::function<void()> > myPair("print", std::bind(&MyObject::printSomeText, this)); 
     functionMap.insert(myPair); 
     functionMap["print"](); 
    } 
    void printSomeText() 
    { 
     std::cout << "Printing some text"; 
    } 
}; 

MyObject o; 
o.testFunctionMap(); 

これは問題なく動作します。 MyObject :: printSomeText関数をペアの値として使用する別の方法はありますか?文字列の関数unordered_mapを作成する方法

答えて

2

はい、ポインタ・ツー・メンバー機能:

std::unordered_map<std::string, void(MyObject::*)()> m; 
m["foo"] = &MyObject::printSomeText; 

// invoke: 
(this->*m["foo"])(); 

これは現在のインスタンス上ではなく、任意のMyObjectインスタンス上のメンバ関数を呼び出すことができます。特別な柔軟性が必要な場合は、代わりにマップタイプをstd::pair<MyObject*, void(MyObject::*)()>にしてください。

関連する問題