将函数指针作为线程池类中的函数模板发送
send function pointer as function template in a threadpool class
我正在尝试使用这个家伙的线程池实现:https://github.com/progschj/ThreadPool
我在向enqueue
方法添加"函数"时遇到问题......下面是 enqueue
方法的实现:
// add new work item to the pool
template<class T, class F>
Result<T> ThreadPool::enqueue(F f)
{
Result<T> res;
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.push_back(std::function<void()>(
[f,res]()
{
CallAndSet<T,F>()(res, f);
}));
}
condition.notify_one();
return res;
}
这是我正在使用的:
#include "ThreadPool.h"
#include <stdio.h>
#include <iostream>
int main() {
// create a thread pool of 4 worker threads
ThreadPool pool(4);
// queue a bunch of "work items"
for(int i = 0; i < 8; ++i) {
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::cout << "world " << i << std::endl;
});
}
}
它是示例代码的一部分,试图展示如何使用库...
编译的输出为:
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
scons: building associated VariantDir targets: build
g++ -o build/main.o -c -std=c++11 -pthread -Wall -g main.cpp
main.cpp: In function 'int main()':
main.cpp:15:7: error: no matching function for call to 'ThreadPool::enqueue(main()::<lambda()>)'
main.cpp:15:7: note: candidate is:
In file included from main.cpp:1:0:
ThreadPool.h:117:15: note: template<class T, class F> Result<T> ThreadPool::enqueue(F)
ThreadPool.h:117:15: note: template argument deduction/substitution failed:
main.cpp:15:7: note: couldn't deduce template parameter 'T'
scons: *** [build/main.o] Error 1
scons: building terminated because of errors.
在模板方面,我一无所知。我不知道为什么以上不起作用...有人有什么想法吗?
干杯
加里特
您必须显式指定 T,因为它不是参数列表的一部分,因此无法减少。
pool.enqueue<TheType>(functor);
我无法仅从片段中猜测 T 应该是什么。
相关文章:
- 如何制作指向模板函数的指针?
- 指向成员函数的模板指针 - getter
- 指向模板上下文中的成员函数或静态函数的指针
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 如何声明指向成员模板函数的指针?
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 努力将指向成员函数的指针绑定到类模板的T成员,然后在槽中调用
- 在C++17中,为什么类模板和函数模板的指针类型推导明显不一致
- C++成员函数模板将成员函数指针作为模板参数
- 使用通用函数指针参数化函数模板的简洁方法
- 带有指向成员函数的指针的模板 =VC++ 2017 和 gcc 5.1 的>不同的错误消息
- 如何获取指向已推断的模板函数的指针?
- 将常量添加到函数模板指针参数
- 使用原始指针作为参数的函数模板推导
- 从具有迭代器参数的模板函数返回指针
- 是否可以从指向成员函数模板参数的指针推断类类型
- 打印函数模板的内容进行类指针
- 接受指向类成员函数的指针的模板参数
- 类型定义模板,接受指向常量和非常量函数的指针
- 字符串和指向模板化函数的指针的映射