schuess
schuess

Reputation: 1079

std::function std::bind with lambda overload ambiguity

Consider the following code

class my_class {
public:
struct my_struct {
   int i;
};
std::function<void(my_struct&)> func;
my_class() {
   func = std::bind([this](my_struct& s) { s.i = 5; });
}
};

On VS 2017 I am receiving the following errors:

error C2440: 'initializing': cannot convert from 'std::_Binder>' to 'std::function' note: No constructor could take the source type, or constructor overload resolution was ambiguous

Any thoughts on what I'm missing to resolve the ambiguity?

Upvotes: 0

Views: 249

Answers (2)

T.C.
T.C.

Reputation: 137414

This is about the most unhelpful compiler error ever. The problem is that you want

func = std::bind([this](my_struct& s) { s.i = 5; }, std::placeholders::_1);
//                                                  ^^^^^^^^^^^^^^^^^^^^^

std::bind(f) means "give me a g such that g(/* anything */) is f().

You need to use placeholders if you want to pass arguments through.

(I assume that your real code does something more complicated than this, because there's no need for bind or for capturing this in the code you've shown.)

Upvotes: 3

Walter
Walter

Reputation: 45484

std::bind is more or less obsolete in C++11. Just use a lambda instead.

class my_class
{
public:
  struct my_struct {
    int i;
  };
  my_class()
  : func ([](my_struct& s) { s.i = 5; }) {}
private:
  std::function<void(my_struct&)> func;
};

Upvotes: 2

Related Questions