C++ lambda with captures as a function pointer

后端 未结 8 793
离开以前
离开以前 2020-11-22 15:35

I was playing with C++ lambdas and their implicit conversion to function pointers. My starting example was using them as callback for the ftw function. This works as expecte

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:02

    Using locally global (static) method it can be done as followed

    template 
    auto cify_no_args(F&& f) {
      static F fn = std::forward(f);
      return [] {
        return fn();
      };
    }
    

    Suppose we have

    void some_c_func(void (*callback)());
    

    So the usage will be

    some_c_func(cify_no_args([&] {
      // code
    }));
    

    This works because each lambda has an unique signature so making it static is not a problem. Following is a generic wrapper with variadic number of arguments and any return type using the same method.

    template 
    struct lambda_traits : lambda_traits
    { };
    
    template 
    struct lambda_traits : lambda_traits
    { };
    
    template 
    struct lambda_traits {
        using pointer = typename std::add_pointer::type;
    
        static pointer cify(F&& f) {
            static F fn = std::forward(f);
            return [](Args... args) {
                return fn(std::forward(args)...);
            };
        }
    };
    
    template 
    inline lambda_traits::pointer cify(F&& f) {
        return lambda_traits::cify(std::forward(f));
    }
    

    And similar usage

    void some_c_func(int (*callback)(some_struct*, float));
    
    some_c_func(cify([&](some_struct* s, float f) {
        // making use of "s" and "f"
        return 0;
    }));
    

提交回复
热议问题