Search code examples
c++templatesboostbindfunctor

c++ function proxy for execution control


I want to make a "function proxy" that:

  1. It is a function object.
  2. It's return type and argument type(s) are "inherited" automatically from a given "base" function type as template argument. the "base" function type could be one of (function pointer / boost::function / boost::bind)
  3. It is initialized with a function object of the given type.
  4. When it is called (as you can call the original function), it is able to store the call into something like boost::bind, and pass it to somewhere else (intentionally, a thread-safe queue, so that it can be invoked later, in another thread.), then return the call's result.

And for now, my problem is how (and is it even possible) to create this (functor) class using template teq, and pass the unknown argument list to bind.

Thanks in advance.


Solution

  • template<typename R, typename... ARGS>
    class Proxy {
      typedef std::function<R(ARGS...)> Function;
      Function f;
     public:
      Proxy(Function _f) : f(_f) {}
      R operator(ARGS... args) {
        std::function<R> bound = std::bind(f, args...);
        send_to_worker_thread(bound);
        wait_for_worker_thread();
        return worker_thread_result();
      }
    };
    
    // Because we really want type deduction
    template<typename R, typename... ARGS>
    Proxy<R,ARGS...>* newProxy(R(*x)(ARGS...)) {
      return new Proxy(std::function<R,ARGS...>(x);
    }
    

    I haven't actually tested this.

    You'll probably want something asynchronous, but I'll leave that to you.