2014-02-20 116 views
2

基本上就是我想要做的是這樣的:延遲函數調用

std::function< int(void) > foo = &getInt; 
int magicNumber = 13; 
std::function< int(void) > delayedAdd = std::bind(std::plus, magicNumber, getInt); 

顯然,這是行不通的。我需要以某種方式包裝getInt調用,以便它恰好在std::plus函數發生之前發生。然後,所有這些都需要推遲,直到我撥打delayedAdd

我正在QObject之外使用Qt5.0所以我不能connect一個lambda到SLOT。但我想要connect,而不是delayedAddSLOT

+標籤funception

回答

3

您可以通過使用std::bind推遲函數調用:

using namespace std; 

int getInt() { 
    cout << "getInt!" << endl; 
    return 42; 
} 

function<int(void)> foo = &getInt; 
int magicNumber = 13; 

cout << "before delayed definition" << endl; 
function<int(void)> delayed = std::bind(plus<int>(), magicNumber, bind(foo)); 
cout << "after delayed definition" << endl; 

int i = delayed(); 

cout << "after delayed call" << endl; 

輸出:

之前延遲定義
延遲定義
getInt後!
延遲呼叫

後,您不需要定義foo像你這樣,無論是。你可以只在delayed定義綁定getInt直接:

function<int(void)> delayed = bind(plus<int>(), magicNumber, bind(getInt)); 

有關的std ::綁定更多詳情,請N3797第20.9.9。
對於更具體的解釋,cppreference說:

的std ::綁定返回類型
...
成員函數運算符() 鑑於從以前的調用獲取綁定對象克,當它在一個函數調用表達式g(u1,u2,... uM)中被調用時,對std :: decay :: type類型的存儲對象進行調用,參數定義如下:
...
- 如果std :: is_bind_expression :: value == true(即另一個綁定子表達式在初始的綁定調用中被用作參數),那麼該綁定子表達式被立即調用並且其結果被傳遞給可調用對象。如果綁定子表達式有任何佔位參數,它們是從U1,U2回升,...
...

+0

Gadzooks!剛剛發生了什麼?什麼類型的綁定返回加號?我認爲綁定返回了一個函數對象! –

+0

有一些事情,你只是不想知道;) –

+0

更嚴重的是,http://stackoverflow.com/questions/6412065/what-is-the-return-type-of-boostbind觸及這個問題,但沒有提供很多細節 –