Can a lambda expression be passed as function pointer?

后端 未结 5 1909
忘掉有多难
忘掉有多难 2021-02-05 02:49

I am trying to pass a lambda expression to a function that takes a function pointer, is this even possible?

Here is some sample code, I\'m using VS2010:

         


        
相关标签:
5条回答
  • 2021-02-05 03:18

    In VC10 RTM, no - but after the lambda feature in VC10 was finalized, the standard committee did add language which allows stateless lambdas to degrade to function pointers. So in the future this will be possible.

    0 讨论(0)
  • 2021-02-05 03:18

    This works in VS2010:

    template<class FunctorT>
    void* getcodeptr(const FunctorT& f) {
      auto ptr = &FunctorT::operator();
      return *(void**)&ptr;
    } 
    
    void main() {
      auto hello = [](char* name){ printf("hello %s\n", name); };
      void(*pfn)(char*) = (void(*)(char*)) getcodeptr(hello);
      pfn("world");
    }
    
    0 讨论(0)
  • 2021-02-05 03:30

    As long as the lambda doesn't use capture clause (i.e. doesn't capture variables from above it), it can be used as a function pointer. VC compiler internally generates anonymous functions with different calling convention so that it can be used without issues.

    0 讨论(0)
  • 2021-02-05 03:37

    You can use std::function for this:

    void fptrfunc(std::function<void (int)> fun, int j)
    {
        fun(j);
    }
    

    Or go completely generic:

    template <typename Fun>
    void fptrfunc(Fun fun, int j)
    {
        fun(j);
    }
    
    0 讨论(0)
  • 2021-02-05 03:41

    No. It cannot. Not dependably at least. I know that VS2010 implements them as object functors. Based on how they work that may be an a priori requirement.

    0 讨论(0)
提交回复
热议问题