因爲我們談論C++而不是C,你應該使用std::function
。它是更安全,你也可以用它做更復雜的事情像測試的存在,結合/柯里...
#include <iostream>
#include <functional>
#using namespace std;
typedef function<void (void)> tVoidFunction;
typedef function<void (int)> tVoidFunctionTakingIntParameter;
typedef function<int (float)> tIntFunctionTakingFloatParameter;
void combinedFunction(tVoidFunction fvoid, tVoidFunctionTakingIntParameter fInt, tIntFunctionTakingFloatParameter fIntFromFloat){
if (fvoid) {
fvoid();
}
if (fInt && fIntFromFloat) {
static const float magicValue = 42.f;
int convertedValue = fIntFromFloat(magicValue);
fInt(convertedValue);
}
}
void helloWorld() {
cout << "Hello World" << endl;
}
int floatToInt(float f) {
return floor(abs(f));
}
void doSomethingWithAnInt(int i) {
cout << "doSomethingWithAnInt: " << i << endl;
}
...
void doWeirdThings() {
combinedFunction(helloWorld, doSomethingWithAnInt, floatToInt);
}
何說明爲什麼這是比C風格的函數指針更好,這裏有一對夫婦(有些人爲的)使用std::bind
和lambda來做一些更有趣的功能性東西的例子:
struct Foo {
void doSomethingWithAnInt(int i) {
cout << "Foo instance @" << this << " got: " << i << endl;
}
}
int doSomethingWithTwoFloats(float f1, float f2) {
return floor(sqrt(abs(f1 + f2)));
}
...
void doWeirderThingsThanBefore() {
Foo someFoo;
auto someFooDoesSomethingWithAnInt = bind(&Foo:doSomethingWithAnInt, &someFoo);
static const float anotherMagicValue = 69.f;
auto doSomethingWithTheMagicValue = bind(&doSomethingWithTwoFloats, anotherMagicValue);
auto helloLambda = [](){
cout << "Hello, Lambda!" << endl;
};
combinedFunction(helloLambda, someFooDoesSomethingWithAnInt, doSomethingWithTheMagicValue);
}
你能澄清嗎?你只需要在C++中使用這種語法的幫助? – Lilshieste
是的,非常。我已經有了我的功能。我只是試圖按照上面的函數的順序來實現一些東西。感謝您的評論。 – Reanimation