【发布时间】:2016-12-14 00:50:57
【问题描述】:
编辑:对 std::bind() 的调用可以替换为其他内容,我只希望 runAsyncTerminateOnException() 使用与 std::async() 相同的签名,就像它的包装器一样
我正在尝试为 std::async() 创建一个包装器。 当直接调用 std::async() 有效时,您知道如何使包装器正常工作吗?
注意:我不会修改 print() 函数签名,这是一个示例。我希望包装器是通用的,并适用于通过直接调用 std::async() 处理的所有可能参数。
谢谢。
#include <iostream>
#include <functional>
#include <future>
template<class Fn, class... Args>
inline auto runAsyncTerminateOnException(Fn&& fn, Args&&... args) {
auto make_call = std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...);
return std::async(std::launch::async, [=]() -> decltype(make_call()) {
try {
return make_call();
} catch (...) {
std::cout << "Terminate Called!" << std::endl;
std::terminate();
}
});
}
struct Foo {
template<class... Args>
void print(Args&&... args) {
printf("Foo::print(%d)\n", std::forward<Args>(args)...);
}
};
int main() {
Foo foo;
std::future<void> future = std::async(std::launch::async, &Foo::print<int>, &foo, 2);
std::future<void> future2 = runAsyncTerminateOnException(&Foo::print<int>, &foo, 2);
// your code goes here
return 0;
}
【问题讨论】: