7

我尝试按照Bjarne Stroustupsfunction模板的解释进行操作。我专门玩过c-function-pointersfunctorslambdasmember-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);

...或者错误在哪里?


背景:

bind下面是使用和function使用成员函数的Bjarnes 示例:

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)

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

4

1 回答 1

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

占位符指的是返回的绑定对象中的参数位置。不要索引g的参数。

于 2011-05-29T19:56:44.633 回答