I came across this curio and don't understand why the use of explicit constructors would cause this to fail.
I was trying to generate and initialize objects from configuration data using lambdas. I found that the lambda could only return a copy of the object if the object's class definition did not use explicit constructors. This code sample is a simplistic example of what I found.
class foo {
public:
explicit foo() : _a(0) {}
explicit foo(int val): _a(val) {}
explicit foo(const foo& o) : _a(o._a) {}
explicit foo(foo&& o) : _a(std::move(o._a)) {}
foo& operator()(const foo& rhs) { if (this != &rhs) { _a = rhs._a; } return *this; }
foo& operator()(foo&& rhs) { _a = std::move(rhs._a); return *this; }
int a() const { return _a; }
void a(int val) { _a = val; }
private:
int _a;
};
auto makeFoo = [](int val) -> foo { return foo(val); };
As written the sample code fails to compile with the following errors on the makeFoo line:
In static member function ‘static foo<lambda(int)>::_FUN(int)’:
error: no matching function for call to ‘foo::foo(foo)’
However, if I remove the 'explicit' tags from the foo constructors, the code compiles just fine.
Can someone enlighten me as to why the constructors cannot be explicit in this lambda?