A clean way to store a function and its (arbitrary-type, arbitrary-number) arguments

前端 未结 4 1285
广开言路
广开言路 2020-12-15 13:45

For a library, I\'d like a function to accept another function and its arguments, then store them all for calling later. The arguments must allow for any mixture of types, b

4条回答
  •  无人及你
    2020-12-15 13:56

    If you want/are able to make use of the C++11 future library you can use std::async

    #include 
    
    auto caller = std::async(myFunc1, 123, 45.6); // Creates a future object.
    
    caller.get(); // Waits for the function to get executed and returns result.
    

    To force lazy evaluation use:

    auto caller = std::async(std::launch::deferred, myFunc1, 123, 45.6);
    

    Also this has the advantage that the function call might be executed on a different thread which makes use of multicore hardware. However this may not be suitable in every case.

提交回复
热议问题