I am trying to implicitly construct an object from a lambda function. The constructor of the object takes a function pointer as parameter. But the code [ 1 ] doesn't compile with the message:
6 : <source>:6:5: note: candidate constructor not viable: no known conversion from '(lambda at /tmp/compiler-explorer-compiler117117-54-dfxyju.lkw98/example.cpp:22:14)' to 'Bar' (aka 'bool (*)()') for 1st argument
Foo(Bar b) : m_b{b} {}
But the standard states that a lambda function is implicitly convertible to a function pointer with the same parameter and return type [ 2 ]. This should be applicable here and therefore I would expect the constructor to be callable.
So why doesn't the code compile? Thanks for your explanations!
[ 1 ] Code example:
using Bar = bool(*)();
class Foo
{
public:
Foo(Bar b) : m_b{b} {}
private:
Bar m_b;
};
int main()
{
// working
Foo f1 ( [](){ return true; });
Foo f2 = Bar( [](){ return true; });
// working implicit conversion
bool(*tmp)() = []() { return true; };
Foo f3 = tmp;
// not working
Foo f4 = [](){ return true; };
return 0;
}
[ 2 ] The C++14 Standard states in section 5.1.2 that:
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
Which means the lambda should be implicitly (non-explicit) convertable to the function pointer.
tested with:
- Clang5.0.0 -std=c++14
- MSVC14.12 /permissive-