Obtaining function pointer to lambda?

前端 未结 3 1177
野的像风
野的像风 2020-12-23 16:35

I want to be able to obtain a function pointer to a lambda in C++.

I can do:

int (*c)(int) = [](int i) { return i; };

And, of cours

3条回答
  •  醉梦人生
    2020-12-23 17:32

    The lambda code doesn't work for the same reason this doesn't work:

    struct foo {
      operator int*() const {
        static int x;
        return &x;
      }
    };
    
    int* pint = foo{};
    auto* pint2 = foo{}; // does not compile
    

    or even:

    template
    void test(T*) {};
    test(foo{});
    

    The lambda has an operator that implicitly converts it to a (particular) function pointer, just like foo.

    auto does not do conversion. Ever. Auto behaves like a class T parameter to a template function where its type is deduced.

    As the type on the right hand side is not a pointer, it cannot be used to initialize an auto* variable.

    Lambdas are not function pointers. Lambdas are not std::functions. They are auto-written function objects (objects with an operator()).

    Examine this:

    void (*ptr)(int) = [](auto x){std::cout << x;};
    ptr(7);
    

    it compiles and works in gcc (not certain if it is an extension, now that I think about it). However, what would auto* ptr = [](auto x){std::cout << x;} supposed to do?

    However, unary + is an operator that works on pointers (and does nearly nothing to them), but not in foo or a lambda.

    So

    auto* pauto=+foo{};
    

    And

    auto* pfun=+[](int x){};
    

    Both work, magically.

提交回复
热议问题