c++ - 将函数放入模板

标签 c++ class templates

我找到了一个线程池类,我尝试了很多组合来调用内部函数的方法。

这是我的尝试示例:

WorkerPool wp(4);
wp.run_task<Connection::On_NET1_LOGIN>(&On_NET1_LOGIN());

这是 WorkerPool 的功能:

 template < typename Task >
  void run_task( Task task )
  {
    boost::unique_lock< boost::mutex > lock( mutex_ );

    // If no threads are available, then return.
    if ( 0 == available_ ) return;

    // Decrement count, indicating thread is no longer available.
    --available_;

    // Post a wrapped task into the queue.
    io_service_.post( boost::bind( &WorkerPool::wrap_task, this,
                                   boost::function< void() >( task ) ) );
  }

private:
  /// @brief Wrap a task so that the available count can be increased once
  ///        the user provided task has completed.
  void wrap_task( boost::function< void() > task )
  {
    // Run the user supplied task.
    try
    {
      task();
    }
    // Suppress all exceptions.
    catch ( ... ) {}

    // Task has finished, so increment count of available threads.
    boost::unique_lock< boost::mutex > lock( mutex_ );
    ++available_;
  }

我在调用该线程池的函数时做错了什么? 谢谢。

最佳答案

您正在尝试像这样添加任务:

wp.run_task<Connection::On_NET1_LOGIN>(&On_NET1_LOGIN());

这似乎有两个问题。

  1. 您不需要指定模板参数,因为它们可以被推断出来。此外,如果您这样做了,您应该指定函数的类型 - 而不是名称。
  2. 您想传递要调用的函数的地址,但您正在尝试调用该函数并获取结果的地址。

要解决这两个问题,请尝试以下操作:

wp.run_task(&Connection::On_NET1_LOGIN);

注意:由于 On_NET1_LOGIN 似乎是 Connection 的成员函数,除非该函数是 static,否则这将不起作用。如果不是这种情况,您需要一个 Connection 实例来调用该函数,并且您需要发送一个执行此操作的函数对象。这可以使用 lambda 或 std::bind 来解决。

关于c++ - 将函数放入模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003238/

相关文章:

c++ - 将 time_duration 转换为 DATE

c++ - 容器类序列 c++

c++ - 如何在编译时找出可以表示数字的最小整数类型

c++ - 双模板函数重载失败

c++ - 实现 is_constexpr_copiable

c++ - 了解 OpenGL 中的 glTexCoord2f()、glVertex3f()

c++ - 如何在 GMOCK 中使用未指定的参数创建返回值?

Python类从父级运行方法,但保留变量

android - 意外的顶级异常向 Android Studio 项目添加新模块

c++ - 如何防止在 OpenGL Qt 中绑定(bind)随机纹理?