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

前端 未结 4 1278
广开言路
广开言路 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:54

    You could use lambda functions to hide the bindings:

    #include 
    
    class DelayedCaller : public std::function< void(void) > {
    public:
        DelayedCaller(std::function< void(void) > fn)
          : std::function< void(void) >(fn) {}
    };
    
    DelayedCaller caller1([]() { myFunc1(123, 45.6); });
    DelayedCaller caller2([]() { myFunc2("A string"); });
    
    caller1(); // Calls myFunc1(), with arguments 123 and 45.6
    caller2(); // Calls myFunc2(), with argument "A string"
    

    This also gives your library's users more flexibility. They're not limited to a single function call and the functions have access to the original environment they were created in:

    int x;
    
    DelayedCaller caller3 = [&x]() {
        if (x == 0)
            DoSomething();
        else
            DoSomethingElse();
    };
    

提交回复
热议问题