c++ - 将成员函数传递给模板函数
问题描述
给定以下功能:
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
return res;
}
将成员函数作为参数传递的正确方法是什么ThreadPool::enqueue
,比如对象是:
Foo foo
功能是:
foo.do_something();
我尝试使用std::bind
andstd::mem_fn
有或没有“&”,但都失败了。
解决方案
除了@IgorTandetnik 在评论中提到的内容之外,您还可以使用std::bind
withstd::mem_fn
将成员函数传递给您的方法:
struct Foo
{
void do_something() {}
void do_something_else(int x, int y, std::string str) {}
};
int main()
{
Foo foo;
ThreadPool pool;
auto func_sth = std::bind(std::mem_fn(&Foo::do_something), foo);
auto func_sth_else = std::bind(std::mem_fn(&Foo::do_something_else), foo, 10 , 11, "hi");
pool.enqueue(func_sth);
pool.enqueue(func_sth_else);
return 0;
}
推荐阅读
- php - 基于第一个字符的条件正则表达式长度
- python - 读取 RAW 图像更大
- reactjs - Mapbox GL、Deck GL 和 React Map GL 之间的底层架构是什么?
- matplotlib - seaborn.swarmplot 符号比例的问题:零没有扩展
- html - 如何使用 EMBED 或 OBJECT html 标签加载本地 mp4 视频文件?可能吗?
- cakephp - CakePHP 4:Cake Bake 错误,找不到文件异常
- java - 线程“WindowsNativeRunloopThread”java.lang.NoSuchMethodError 中的异常:
当我执行 .jar 文件时 - php - wp_safe_redirect(); 不是重定向,它只是打印给定的变量?
- javascript - 用JS改变视频分辨率
- sql-server - 根据同一字段中的值计算百分比