2012-09-21 35 views
7

成員函數有一個隱含的指針參數this。爲什麼std::function接受這個簽名,那麼,S是一個簡單的類嗎? (complete sample爲什麼std :: function在簽名中接受這個引用?

std::function<void(S &)> func = &S::foo; 

調用它的工作原理也是如此,並區分對象:

S s1 = {5}; 
S s2 = {6}; 

func(s1); //prints 5 
func(s2); //prints 6 

什麼我通常想到的是,它需要一個指針,它的工作原理,以及:(complete sample

std::function<void(S * const)> func = &S::foo; 

S s1 = {5}; 
S s2 = {6}; 

func(&s1); //prints 5 
func(&s2); //prints 6 

當隱式this參數是一個指針時,爲什麼第一個函數會傳遞成員函數的引用?

回答

3

std::function<SIG>可以從很多行爲類似於函數的東西構造出來,將它們轉換爲合適的對象std::function

在這種情況下void S::foo()的行爲很像一個功能void foo_x(S&)(如它們都需要一個S打電話,並可能修改S,返回什麼)。因此std::function<void(S&)>提供了一個將成員函數轉換爲函數對象的構造函數。即

std::function<void(S &)> func = &S::foo; 

使用構造函數,像std::function<void(S&)>(void(S::)()),創造的東​​西相當於:

void foo_x(S & s) { return s.foo(); } 
std::function<void(S&)> func = foo_x; 

同樣,

std::function<void(S * const)> func = &S::foo; 

相當於

void foo_x(S * const s) { return s->foo(); } 
std::function<void(S* const)> func = foo_x; 

通過構造函數如std::function<void(S* const)>(void(S::)())

+2

這是一個非常豐富的閱讀,謝謝。當你認爲'std :: function'獨立於原始函數指針並且有能力做它喜歡的事情來增加它所包裝的東西的可用性時,它會更有意義。 – chris

5

因爲std::function被正確設計。 this是一個指針的事實是歷史事故和成員函數內部的細節。這個事實不應該影響功能用戶的設計決定。

當簽名中的第一個參數類型是引用時,std::function的設計者正確地決定接受成員函數。

相關問題