概述
关于模板函数完美转发传递成员函数的问题
以下模板函数转移传递进来的函数
template<class F, class... Args>
auto commit(F&& f, Args&&... args) ->std::future<decltype(f(args...))> {
if (stop.load()) {
throw std::runtime_error("task executor have closed commit.");
}
using ResType = decltype(f(args...));
auto task = std::make_shared<std::packaged_task<ResType()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
{
std::lock_guard<std::mutex> lock{ m_task };
tasks.emplace([task]() {
(*task)();
});
}
cv_task.notify_all();
std::future<ResType> future = task->get_future();
return future;
}
因为传递成员函数需要this指针,例如std::thread(&class::func,this,args…);
所以需要使用std::mem_fn转化成员函数
void f() {
return;
}
class G {
public:
ilovers::TaskExecutor executor{ 10 };
G(){
auto a = std::mem_fn(&G::f);
std::future<int> gg = executor.commit(a,this,1);//编译通过
}
int f(int i) {
return i;
}
int operator()(int i) {
return i;
}
};
int main() {
ilovers::TaskExecutor executor{ 10 };
std::future<void> ff = executor.commit(f);//编译通过
G g;
auto a = std::mem_fn(&G::f);
auto c = std::mem_fn(&G::operator());
std::future<int> gg = executor.commit(c, g, 1);//编译通过
std::future<int> gg = executor.commit(a,g,1);//编译通过
std::future<std::string> fh = executor.commit([]()->std::string { return "hello"; });
最后
以上就是淡然小笼包为你收集整理的成员函数的完美转发关于模板函数完美转发传递成员函数的问题的全部内容,希望文章能够帮你解决成员函数的完美转发关于模板函数完美转发传递成员函数的问题所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复