C ++ Using lambda to implicitly call a constructor waiting for a function pointer

I am trying to implicitly construct an object from a lambda function. The constructor of the object takes a pointer to the function as a parameter. But the code [1] does not 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 converted to a function pointer with the same parameter and return type [2]. This should be applicable here, and so I would expect the constructor to be callable.

So why doesn't the code compile? Thanks for your explanation!


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

https://godbolt.org/g/QE4v1Z


[2] C ++ 14 Standard states in section 5.1.2 that:

- - const, , , . , , , , .

, () .


:

  • Clang5.0.0 -std = ++ 14
  • MSVC14.12/permissive -
+4
1

, ; bool(*tmp)() = []() { return true; };. , .

:

  • ;
  • ;
  • .

, ( ).

Foo f4 = [](){ return true; };, , lambda lambda, Foo Foo, , .

BTW:

  • Foo f1 ( [](){ return true; }); , direct intialization Foo; lambda , , .

  • Foo f2 = Bar( [](){ return true; }); , lambda , Foo.

  • bool(*tmp)() = []() { return true; }; Foo f3 = tmp; , tmp, tmp Foo; , .

  • Foo f5 = +[](){ return true; }; , operator+ lambda, , , +[](){ return true; } bool(*)(), , f2.

+14

Source: https://habr.com/ru/post/1690394/


All Articles