Edamame
Edamame

Reputation: 25366

std::bind: error: too few arguments to function call, single argument was not specified

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);

Upvotes: 1

Views: 3455

Answers (1)

templatetypedef
templatetypedef

Reputation: 372704

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); }

Upvotes: 3

Related Questions