开发者

C++0x function<>, bind and members

I tried to follow Bjarne Stroustups explanation of the function template. I specifically played with the interchangability of c-function-pointers, functors, lambdas and member-function-pointers

Given the defintions:

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, ...

I want to assign to function<float(int,int)> everything possible:

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
}

And the last line gives a typical unreadable compiler-template-error. sigh.

I want to bind f to an existing x instances member function, so that only the signature float(int,int) is left.

What should be the line instead of

f = bind(g, &x,_2,_3);

...or where else is the error?


Background:

Here comes Bjarnes example for using bind and function with a member 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)

I thought bind is used this way: The un-assigned places get placeholders, the rest is filled in the bind. Should _1 nut get this, then`? And therefore the last line be:

function<int (int)> ff = std::bind(f,&x,_2)

On Howards suggestion below I tried it :-)

C++0x function<>, bind and members


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

The placeholders refer to the argument positions in the returned bind object. The don't index g's parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜