# boost.bind + member function

This topic is 4471 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was playing a little with the boost.bind library and I tried to bind a function member from one class (and the binding is also done in this class) to a member function (boost.function) from another class. So I wrote quickly some small test code: //session.h
class session
{
public:
session() {;}

void execcommand (int val) {std::cout << "AANGEROEPEN" << std::endl;}

{
Newuser.ClientmsgRelay = boost::bind( std::mem_fun(&session::execcommand), this);
}

user Newuser;
};

//user.h
class user
{
public:
user () {;}
boost::function<void (int)> ClientmsgRelay;
};

//main.cpp
int main()
{
session test;
test.Newuser.ClientmsgRelay (1);
return 0;
}

When I do it this way I get compiler errors, but when I use 'the old way'
void sessionlink ()
{
Newuser.ClientmsgRelay = std::bind1st(
std::mem_fun(&session::execcommand), this);
}

I don't have any problems. Now I'm wondering what's the difference between the two? Or what did I do wrong? Thanks in advance

##### Share on other sites
Quote:
 Original post by Rip7I don't have any problems. Now I'm wondering what's the difference between the two? Or what did I do wrong?

Well, the first and most obvious thing you did wrong was not post the related error(s).

In second place, you need to read the bind() documentation, because your use of it is pretty far fetched from any examples shown of it.

This is wrong: boost::bind( std::mem_fun(&session::execcommand), this);

This might be right: boost::bind( & session::execcommand , this , _1 );

Breakdown: bind() expects to handle the member function itself, so an intermediary functor like mem_fun isn't typically used, and if valid, only serves to limit your options. Since it is a member function, the first, implicit "this" argument must be passed. Then there's the first explicit argument, the integer. _1 is a lambada placeholder, meaning "put the first argument here". Thus, calling:

boost::bind( & session::execcommand , this , _1 )( 42 );

Is equivilant to:

this->*(&session::execcommand)( 42 );

Just to throw in another example, these would produce the same results:

boost::bind( & session::execcommand , _1 , 42 )( this );
boost::bind( & session::execcommand , _1 , _2 )( this , 42 );
boost::bind( & session::execcommand , this , 42 )();

##### Share on other sites
Now it works indeed perfectly.

I'd better read the documentation more thoroughly :)

1. 1
Rutin
44
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632983
• Total Posts
3009708
• ### Who's Online (See full list)

There are no registered users currently online

×