1

I have the following code:

void MyClass::create_msg(MyTime timestamp) {
   // do things here ...
}

and I tried to create a std::bind for the above function:

MyMsg MyClass::getResult(MyTime timestamp) {
   // do things here ...
   std::bind(create_msg(), timestamp);
   // do things ...
}

But got the following error:

error: too few arguments to function call, single argument 'timestamp' was not specified
    std::bind(create_msg(), timestamp);
              ~~~~~~~~~~ ^
MyClass.cpp:381:1: note: 'create_msg' declared here
void MyClass::create_msg(MyTime timestamp) {
^
1 error generated.

What did I do wrong in this case? Thanks!

By the way, same error if I do:

std::bind(&MyClass::create_msg(), this, timestamp);
pstrjds
  • 16,840
  • 6
  • 52
  • 61
Edamame
  • 23,718
  • 73
  • 186
  • 320
  • Is there a reason to use `bind` over a lambda? – clcto Dec 20 '18 at 22:38
  • 1
    @pstrjds but it is a member function so it has to be `std::bind(&MyClass::create_msg, this, timestamp)` – clcto Dec 20 '18 at 22:40
  • @clcto - You are correct - my bad. I was typing quickly and forgot to take into account that it is a member function. – pstrjds Dec 20 '18 at 22:41
  • 2
    In `&MyClass::create_msg()` lose the brackets -> `&MyClass::create_msg` – user4581301 Dec 20 '18 at 22:44
  • Additional worthwhile reading: [How std::bind works with member functions](https://stackoverflow.com/questions/37636373/how-stdbind-works-with-member-functions) – user4581301 Dec 20 '18 at 22:50

1 Answers1

3

There are three issues here.

First, the argument you're giving to std::bind as your function is currently create_msg(). This means "call create_msg, take whatever result it produces, and pass that in as the first argument to std::bind." That's not what you want - you instead meant "take create_msg and pass it as the first parameter to std::bind." Since create_msg is a member function, you'll need to get a pointer to it like this:

std::bind(&MyClass::create_msg, /* ... */)

That will address one issue, but there's another one that will then pop up. When you use std::bind with a member function pointer, you need to prove std::bind with an extra parameter corresponding to the receiver object to use when calling that member function. I believe that in your case you want the current object to be the receiver, which would look like this:

std::bind(&MyClass::create_msg, this, timestamp)

That should work properly.

However, one could argue that there's a third issue here - rather than using std::bind, why not just use a lambda expression?

[timestamp, this] { create_msg(timestamp); }
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065