重複の可能性:
関数ポインターはどのように機能しますか?
関数をパラメーターとしてどのように渡しますか?
また、別のクラスの関数をパラメーターとして渡すことはできますか(オブジェクトを使用しますか?)?
重複の可能性:
関数ポインターはどのように機能しますか?
関数をパラメーターとしてどのように渡しますか?
また、別のクラスの関数をパラメーターとして渡すことはできますか(オブジェクトを使用しますか?)?
関数ポインタの他に、std::function と std::bind (またはboost
C++11 がない場合は同等のもの) を使用できます。これらはポリモーフィックな関数ラッパーを提供するので、この関数を定義するようなことができます。この関数は、std::function
2 つの int を取り、double を返します。
double foo(std::function<double(int, int)> f) {
return 100*f(5,89);
}
次に、その署名に一致するものなら何でも渡すことができます。次に例を示します。
struct Adder {
double bar(double a, double b) { return a+b;}
};
int main() {
using namespace std::placeholders;
Adder addObj;
auto fun = std::bind(&AdderC::bar, &addObj, _1, _2); // auto is std::function<double(int,int)>
std::cout << foo(fun) << "\n"; // gets 100*addObj.bar(5,89)
}
これらはどちらも強力で使いやすく、役に立たない例に惑わされないでください。プレーン関数、静的関数、メンバー関数、静的メンバー関数、ファンクターなどをラップできます。
2つの方法があります。
1つは、関数ポインター@dusktreaderのアウトラインです。
もう1つは、ファンクターまたは関数オブジェクトを使用することです。ここでoperator()
は、関数のパラメーターでオーバーロードするクラスを定義してから、クラスのインスタンスを渡します。
私は常に後者の方が直感的だと思っていますが、どちらでもかまいません。
関数ポインタを渡す必要があります。構文はそれほど難しくありません。ここには、cおよびc++での関数ポインターの使用方法の完全な内訳を提供するすばらしいページがあります 。
そのページ(http://www.newty.de/fpt/fpt.html)から:
//------------------------------------------------------------------------------------
// 2.6 How to Pass a Function Pointer
// <pt2Func> is a pointer to a function which returns an int and takes a float and two char
void PassPtr(int (*pt2Func)(float, char, char))
{
int result = (*pt2Func)(12, 'a', 'b'); // call using function pointer
cout << result << endl;
}
// execute example code - 'DoIt' is a suitable function like defined above in 2.1-4
void Pass_A_Function_Pointer()
{
cout << endl << "Executing 'Pass_A_Function_Pointer'" << endl;
PassPtr(&DoIt);
}