Without using boost::thread and boost::bind directly, is there a way to implement the equivalent of the following code?
std::string func()
{
std::string str("Hello from async task!");
return str;
}
int main()
{
auto ftr = std::async(&func);
std::cout << "Hello from main!";
std::string str = ftr.get();
std::cout << str << std::endl;
return 0;
}
Specifically, this part: auto ftr = std::async(&func); ?
Certainly. Simply make
async<T>(std::function<T()>)return a future which invokesfunc()the moment it’s first waited-for. You won’t get any asynchronicity, but the API doesn’t actually guarantee that the function will run asynchronously, so that’s not a problem.If you have access to an OS-specific threading library, you could of course use that as well.
Note, however, that storing exceptions cannot be implemented portably; it requires additional support from the C++ implementation, unless you can restrict the exceptions supported to ones with a polymorphic clone function. See this question for more information.
The final implementation might look a bit like this (untested):