Nick Golob
Nick Golob

Reputation: 53

C++ lambda conversion -- why is candidate constructor not viable: no known conversion from lambda to std::function

Question about implicit lambda conversions. I have this type:

class A {
 public:
  A(std::function<void(std::string)> func) {
    ....
  }
};

Which I believe has a valid copy constructor.

As I would like to do the following

A a = [](std::string param) { ... };

Or

void MyFunc(A a) { ... }  // definition

MyFunc([](std::string param) { ... });  // call

Yet both these yield compile error:

note: candidate constructor not viable: no known conversion from '(lambda at ....)' to 'std::function' for 1st argument

Why is this? Or should this be possible?

Upvotes: 3

Views: 2445

Answers (1)

Jarod42
Jarod42

Reputation: 217145

Your problem is that only one user conversion is allowed and you need two:

  • lamba -> std::function -> A.

Both

A a{[](std::string) {}};
MyFunc({[](std::string) {}});

work.

Upvotes: 9

Related Questions