Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-) order of args in bind

like image 275
towi Avatar asked May 29 '11 19:05

towi


1 Answers

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.

like image 122
Howard Hinnant Avatar answered Nov 15 '22 10:11

Howard Hinnant