7

Bjarne Stroustupsのテンプレートの説明に従ってみましたfunction。私は特にc-function-pointersfunctorlambdasmember-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に、既存のインスタンス メンバー関数にバインドしたいと考えています。xfloat(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)

以下のハワードの提案で、私はそれを試しました:-)バインド内の引数の順序

4

1 に答える 1

8
f = bind(g, &x,_1,_2); // OK

プレースホルダーは、返されたバインドオブジェクトの引数の位置を参照します。gのパラメータにインデックスを付けないでください。

于 2011-05-29T19:56:44.633 に答える