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

前端 未结 4 1284
广开言路
广开言路 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 14:06

    If your only concern is to hide the argument binding from the callsite while keeping your interface, use variadic templates

    class DelayedCaller
    {
    public:
      template
      static DelayedCaller* setup(void (functionPtr*)(Args...), Args&&... args)
      {
        return new DelayedCaller(std::bind(functionPtr, std::forward(args)...));
      }
    
      DelayedCaller(const std::function& f) : f(f) {}
    
    private:
      std::function f;
    };
    

    The public constructor still offers your users the possibility to initialize it with a lambda is they wish.

提交回复
热议问题