2010-06-01 14 views
0

我還有一個關於函數引用的問題。 例如,我有這樣的定義:使用函數引用

typedef boost::function<bool (Entity &handle)> behaviorRef; 
std::map< std::string, ptr_vector<behaviorRef> > eventAssociation; 

的第一個問題是:怎樣將值插入諸如地圖對象?

我想:

eventAssociation.insert(std::pair< std::string, ptr_vector<behaviorRef> >(eventType, ptr_vector<behaviorRef>(callback))); 

但錯誤:

no matching function for call to ‘boost::ptr_vector<boost::function<bool(Entity&)> >::push_back(Entity::behaviorRef&)’ 

我undersatnd它,但是無法進行可行的代碼。

第二個問題是如何調用這些函數? 例如,我有一個行爲參考的對象,如何通過boost :: bind來調用它與傳遞我自己的值?

+1

作爲前端,則可以使用'的std :: make_pair()的',而不是直接構建在一對;這可以避免必須寫出對的模板參數。 – 2010-06-01 13:22:48

+0

@ james-mcnellis感謝您的提示! – Ockonal 2010-06-01 13:25:33

回答

2

PART 1

沒有必要使用ptr_vectorboost::function具有值語義,因此可以存儲在標準容器中。所以下面應該工作:

typedef boost::function<bool (Entity &handle)> behaviorRef; 
std::map< std::string, std::vector<behaviorRef> > eventAssociation; 

eventAssociation.insert(std::make_pair(eventType, vector<behaviorRef>(1, callback))); 

注意兩個參數的構造函數vector

如果你確實需要一個ptr_vector(因爲你使用的是不可複製型),你需要像下面這樣,因爲ptr_vector不具有填充載體構造:

ptr_vector<behaviorRef> behaviours; 
behaviours.push_back(new behaviourRef(callback)); 
eventAssociation.insert(std::make_pair(eventType, behaviours)); 

第2部分

沒有必要使用boost::bind來調用函數(儘管您可以使用它來首先製作它)。用於調用它的語法是一樣的正常功能:

behaviourRef behaviour; 
Entity entity; 
bool result = behaviour(entity); 
+0

謝謝,但我不明白爲什麼你將兩個argmuments傳遞給std :: vector? – Ockonal 2010-06-01 13:53:41

+2

@Ockonal:第一個參數是向量的大小(即它最初保存的對象的數量),第二個參數是一個將用於複製構建最初創建的對象的對象。例如:'vector (10,some_foo)'創建一個載體,其中包含10個some_foo的克隆 – 2010-06-01 14:00:45

+0

好的,太棒了!謝謝。 – Ockonal 2010-06-01 14:03:39

3

第一個問題:

ptr_vector<Foo>包含指向富。因此,如果您需要使用ptr_vector(可能是因爲您的函數對象複製開銷很大),則必須將指針push_back指向行爲參考。

第二個問題,第一部分:

甲behaviorRef被稱爲具有相同語法比bool(Entity&)功能:

// Somehow get an Entity and a behaviorRef 
Entity some_entity = ...; 
behaviorRef some_behavior = ...; 

// Call the behaviorRef 
bool result = some_behavior(some_entity); 

第二個問題,第二部分:

甲behaviorRef可以以與另一個函數對象相同的方式與boost :: bind一起使用:

// Somehow get an Entity and a behaviorRef 
Entity some_entity = ...; 
behaviorRef some_behavior = ...; 

// Make a new function object, bound to some_entity 
boost::function<bool()> bound_behavior = boost::bind(some_behavior, some_entity); 

// Call the bound function. 
bool result = bound_behavior(); 
+0

第二個問題的答案很好,謝謝!很遺憾,我不能標出兩個答案。 – Ockonal 2010-06-01 13:56:21