Passing capturing lambda as function pointer

前端 未结 9 2246
-上瘾入骨i
-上瘾入骨i 2020-11-21 06:58

Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.

Consider the follo

9条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:25

    A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):

    #include 
    
    
    template
    struct function_traits;
    
    template 
    struct function_traits {
        typedef Ret(*ptr)(Args...);
    };
    
    template 
    struct function_traits : function_traits {};
    
    template 
    struct function_traits : function_traits {};
    
    using voidfun = void(*)();
    
    template 
    voidfun lambda_to_void_function(F lambda) {
        static auto lambda_copy = lambda;
    
        return []() {
            lambda_copy();
        };
    }
    
    // requires C++20
    template 
    auto lambda_to_pointer(F lambda) -> typename function_traits::ptr {
        static auto lambda_copy = lambda;
        
        return [](Args... args) {
            return lambda_copy(args...);
        };
    }
    
    
    
    int main() {
        int num;
    
        void(*foo)() = lambda_to_void_function([&num]() {
            num = 1234;
        });
        foo();
        std::cout << num << std::endl; // 1234
    
        int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
            num = a;
            return a;
        });
        std::cout << bar(4321) << std::endl; // 4321
        std::cout << num << std::endl; // 4321
    }
    

提交回复
热议问题