Bjarne Stroustupsのテンプレートの説明に従ってみましたfunction
。私は特にc-function-pointers、functor、lambdas、member-function-pointersの互換性を試しました
定義を考えると:
struct IntDiv { // functor
float operator()(int x, int y) const
{ return ((float)x)/y; }
};
// function pointer
float cfunc(int x, int y) { return (float)x+y; }
struct X { // member function
float mem(int x, int y) const { return ...; }
};
using namespace placeholders; // _1, _2, ...
可能なすべてのものに割り当てたいfunction<float(int,int)>
:
int main() {
// declare function object
function<float (int x, int y)> f;
//== functor ==
f = IntDiv{}; // OK
//== lambda ==
f = [](int x,int y)->float { return ((float)y)/x; }; // OK
//== funcp ==
f = &cfunc; // OK
// derived from bjarnes faq:
function<float(X*,int,int)> g; // extra argument 'this'
g = &X::mem; // set to memer function
X x{}; // member function calls need a 'this'
cout << g(&x, 7,8); // x->mem(7,8), OK.
//== member function ==
f = bind(g, &x,_2,_3); // ERROR
}
そして最後の行は、典型的な判読不能なコンパイラ テンプレート エラーを示します。ため息。
署名のみが残るようf
に、既存のインスタンス メンバー関数にバインドしたいと考えています。x
float(int,int)
の代わりに何をすべきか
f = bind(g, &x,_2,_3);
...または他のどこにエラーがありますか?
バックグラウンド:
Bjarnesのメンバー関数を使用bind
した例を次に示します。function
struct X {
int foo(int);
};
function<int (X*, int)> f;
f = &X::foo; // pointer to member
X x;
int v = f(&x, 5); // call X::foo() for x with 5
function<int (int)> ff = std::bind(f,&x,_1)
このように使用されると思い bind
ました: 割り当てられていない場所は になりplaceholders
、残りは に埋められbind
ます。では、_1
ナットは を取得する必要がありますか? this
したがって、最後の行は次のようになります。
function<int (int)> ff = std::bind(f,&x,_2)
以下のハワードの提案で、私はそれを試しました:-)