您可以通過在其析構函數中調用function2
的值從function1
返回一個幫助對象。
考慮這個例子:
#include <iostream>
using namespace std;
void function2(int i, int j) {
cout << "function2 called with " << i << " and " << j << endl;
}
struct Function2Caller {
Function2Caller(int param1, int param2) : m_param1(param1), m_param2(param2) {}
~Function2Caller() { function2(m_param1, m_param2); }
int m_param1, m_param2;
};
Function2Caller &operator<<(Function2Caller &obj, int x) {
cout << "Streaming " << x << endl;
return obj;
}
Function2Caller function1(int i, int j) {
cout << "function1 called with " << i << " and " << j << endl;
return Function2Caller(i, j);
}
int main() {
function1(2, 3) << 4 << 6;
}
這個程序打印
function1 called with 2 and 3
Streaming 4
Streaming 6
function2 called with 2 and 3
的想法是,在你行的末尾,在Function2Caller
對象超出範圍,然後析構函數不工作。
請注意,執行此操作時,您應該禁止複製Function2Caller對象,並且使function1
成爲唯一可以調用Function2Caller
構造函數的人。
你說的意思是「無法存儲'param1'和'param2'」傳遞函子?如果在'function1'對象和各種'operator <<'調用的構造之間不能保留這些對象,那麼在將來的函數調用中如何使用它們呢? – 2010-08-30 08:50:56
請注意,由於函數參數的評估順序未指定,因此可以在obj2和obj3之前評估string4。那真的是你想要的嗎? – Chubsdad 2010-08-30 10:24:20
@chubsdad:可以先評估string4,但這並不意味着它首先被髮送到流中。這裏的語義與iostreams相同。 – Potatoswatter 2010-08-30 10:29:59