[英]template function to launch a class member function with std::async
I'd like to write a template function, which can take object of any class/struct and call any of its member function in a thread. 我想编写一个模板函数,它可以获取任何类/结构的对象,并在线程中调用其任何成员函数。 Following does not compile, I guess it can not figure out: std::result_of< F(Args...) >::type
. 以下不编译,我猜它无法搞清楚: std::result_of< F(Args...) >::type
。
Any suggestion, help..? 任何建议,帮助..?
class test_f {
public:
int f(int m) {
std::cout << " call f : " << m << std::endl;
return 1;
}
};
template<typename F, typename T, typename... Args>
std::future<typename std::result_of<F(Args...)>::type>
Async(F&& f, T&& t, Args&&... params) {
return(std::async(std::launch::async, std::forward<F>(f),
std::forward<T>(t), std::forward<Args>(params)...));
}
int main() {
test_f tf ;
auto a = Async(&test_f::f, &tf, 1) ;
}
If you can use C++14, just use auto
: 如果你可以使用C ++ 14,只需使用auto
:
template<typename F, typename T, typename... Args>
auto Async(F&& f, T&& t, Args&&... params) {
return(std::async(std::launch::async, std::forward<F>(f),
std::forward<T>(t), std::forward<Args>(params)...));
}
Otherwise you need something like this: 否则你需要这样的东西:
auto Async(F&& f, T&& t, Args&&... params)
-> std::future<decltype(
(t->*f) (std::forward<Args>(params)...) )>
)> { // .. same as before
You're just missing an argument in your result_of
declaration. 你只是在result_of
声明中错过了一个参数。 Your function F
takes a T
and Args...
and you forgot the T
: 你的函数F
需要T
和Args...
而你忘了T
:
template<typename F, typename T, typename... Args>
std::future<typename std::result_of<F(T, Args...)>::type>
// ^^^^
Async(F&& f, T&& t, Args&&... params) {
return(std::async(std::launch::async, std::forward<F>(f),
std::forward<T>(t), std::forward<Args>(params)...));
}
Alternatively, the T
is totally unnecessary since you're arbitrarily limiting yourself to 1+ argument functions. 或者, T
是完全没必要的,因为你任意限制自己的1+参数函数。 And it's easy to forget. 它很容易忘记。 So you can just drop it: 所以你可以放弃它:
template<typename F, typename... Args>
std::future<typename std::result_of<F(Args...)>::type>
Async(F&& f, Args&&... params) {
return(std::async(std::launch::async, std::forward<F>(f),
std::forward<Args>(params)...));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.