且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过通用类型替换模板函数指针

更新时间:2021-09-14 09:13:13

如果我理解,下面是你需要的:

If I understand, below is what you require:

class Queue
{
private:
  std::queue<std::function<void()>> queue;    /**< the messaging queue, appended to using enqueue(), popped from using dequeue() */
public:

  // pass in the instance of the object and simply allow the compiler to deduce the function pointer nastiness...
  template<typename T, typename F, typename... Args>
  void enqueue(T instance, F func, Args... args)
  {
    queue.push(std::bind(func, instance, args...));
  }

  int dequeue()
  {
    if(!queue.empty())
    {
      queue.front()();
      queue.pop();
    }
  }
};

哦和如何使用它:

struct foo
{
  void bar(int a)
  {
    std::cout << "foo::bar: " << a << std::endl;
  }
};

struct bar
{
  void foo(int a, int c)
  {
    std::cout << "bar::foo: " << (a  + c)<< std::endl;
  }
};

int main(void)
{
  Queue q;
  foo f;
  bar b;
  q.enqueue(&f, &foo::bar, 10);
  q.enqueue(&b, &bar::foo, 10, 11);

  q.dequeue();
  q.dequeue();
}

应输出:

foo::bar: 10
bar::foo: 21


b $ b

或者,更好的是,更改函数签名,并允许用户将 std :: function !这是正常的方式(参见例如 boost :: asio :: io_service :: post 。)

Or, even better, change your function signature and allow users to enqueue a std::function! This is the "normal" way (see for example, boost::asio::io_service::post.)

编辑:这是一个简单的例子:

Here is a simple example:

// Let the compiler do all the hard work for you..
template<typename T>
void enqueue(T f)
{
  queue.push(f);
}

现在可以将任何函数发布到此队列...

Now to post any function to this queue...

// Here you are posting the functor itself...
q.enqueue(std::bind(&bar::foo, &b, 15, 12));