gpt4 book ai didi

c++ - 将函数放入模板

转载 作者:行者123 更新时间:2023-11-28 07:17:32 24 4
gpt4 key购买 nike

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

这是我的尝试示例:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com