C++ 0x函数<>,绑定和成员

tow*_*owi 7 functional-programming bind member-function-pointers c++11

我试图按照Bjarne Stroustupsfunction模板的解释.我特别使用了c-function-pointers,functors,lambdasmember-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, ...
Run Code Online (Sandbox Code Playgroud)

我想分配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
}
Run Code Online (Sandbox Code Playgroud)

最后一行给出了一个典型的不可读的编译器模板错误.叹了口气.

我想绑定f到现有的x实例成员函数,以便只float(int,int)留下签名.

什么应该是线而不是

f = bind(g, &x,_2,_3);
Run Code Online (Sandbox Code Playgroud)

......或者错误在哪里?


背景:

以下是Bjarnes使用bindfunction使用成员函数的示例:

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)
Run Code Online (Sandbox Code Playgroud)

以为 bind是用这种方式:未分配的地方得到placeholders,其余的填充在bind.如果_1坚果得到this,那么`?因此,最后一行是:

function<int (int)> ff = std::bind(f,&x,_2)
Run Code Online (Sandbox Code Playgroud)

下面的霍华德建议我尝试了:-)绑定中的args顺序

How*_*ant 8

f = bind(g, &x,_1,_2); // OK
Run Code Online (Sandbox Code Playgroud)

占位符引用返回的绑定对象中的参数位置.不要索引g的参数.