2011-03-22 64 views
3

我的問題與this one類似。我需要存儲指向地圖中成員函數的指針。成員函數需要一個參數,在構建地圖時必須綁定一個特定的值。我怎麼做?地圖應該有一個binder2nd對象作爲它的值。如何在地圖中使用存儲指向成員函數指針的Binder2nd對象?

如:

enum { FOO, BAR }; 

exMap["foo"] = bind2nd(&classA::Func, FOO); 

我不知道如何聲明此地圖。

+0

你能說說你想達到什麼嗎? 你想要存儲這些東西的目的是什麼? 目前還不清楚你爲什麼使用地圖。元素的分配是什麼? 在oterh的話,你想成爲你的鑰匙在地圖上? – 2011-03-22 10:42:09

+0

我在enum上有一個開關箱的func。枚舉字符串作爲命令行參數傳遞,我在地圖中查找並調用與字符串 – excray 2011-03-22 10:49:15

+0

的枚舉轉換綁定的函數,我發佈了一個考慮上述細節的答案。 – 2011-03-22 12:17:15

回答

2

下面是一個使用作品的Boost.Function例如:

#include "boost/function.hpp" 
#include <map> 
#include <iostream> 
#include <functional> 

struct Foo { 
    void bar(int x) { 
     std::cout << "bar called with x=" << x << std::endl; 
    } 
}; 

int main() 
{ 
    Foo foo; 
    std::map<int, boost::function<void (Foo*)> > m; 

    m[1] = std::bind2nd(std::mem_fun(&Foo::bar), 3); 

    m[1](&foo); 

    return 0; 
} 

顯然,這是不可能的binder2nd,因爲它不是默認 - 構造的,這是一個std::map的值的要求。

由於您無法使用Boost,因此您必須編寫自己的聯編程序。

+0

我無法使用提升。對不起,忘了提。 – excray 2011-03-22 10:50:29

+2

@Vivek:那麼你將不得不編寫自己的綁定器,因爲'binder2nd'不能用在'std :: map'中,因爲它不是默認構造的。 – 2011-03-22 10:55:30

0

正如我從你的評論理解到的問題,你需要一個從字符串映射到枚舉,然後你想調用一個函數與枚舉值。
如果是這樣,爲什麼你使用粘合劑使事情複雜化?

你可以簡單地這樣做:

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

callYourFunction(yourMap[yourStringFromInput]); 

類型的地圖是:

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

和功能的原型:

SomeReturnType callYourFunction(YourEnumType e); 

就是這樣,沒有更多的粘合劑;)

1

而不是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); 
    } 
} 

setup函數「結合」指針成員函數和參數爲字符串鍵。

Caller函數封裝了在地圖中找到該對的混亂業務並執行調用。

相關問題