Last active
May 8, 2018 01:24
-
-
Save goldshtn/7433212 to your computer and use it in GitHub Desktop.
A single function that uses a bunch of C++11/14 features and for "old-school" C++ developers will not even read like C++ anymore.Specifically, it uses:- lambda functions (C++11) with generalized capture semantics (C++14)- rvalue references (C++11)- auto variables (C++11)- decltype and trailing function return type syntax (C++11)- std::move and s…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <future> | |
using namespace std; | |
template <typename Fn, typename... Args> | |
auto do_async_with_log(ostream& os, Fn&& fn, Args&&... args) -> | |
future<decltype(fn(args...))> | |
{ | |
os << "[TID=" << this_thread::get_id() | |
<< "] Starting to invoke function..." << endl; | |
auto bound = bind(fn, forward<Args&&...>(args...)); | |
return async([b=move(bound),&os]() mutable { | |
auto result = b(); | |
os << "[TID=" << this_thread::get_id() | |
<< "] ...invocation done, returning " << result << endl; | |
return result; | |
}); | |
} |
Simply... wow...
@goldshtn: can you show a usage of that function?
@pmalek pass it an ostream, a functor and arguments and it will execute:
auto check_answer = [](int x) { return x == 42; };
auto future_answer = do_async_with_log(cout, check_answer, 41);
return future_answer.get();
But I do have a few comments.
-
On line 12 the correct syntax is
forward<Args>(args)...
-
async
has this kind ofbind
functionality built-in so I would consider using it:return async([fn = forward<Fn>(fn), &os](auto&&... args) { auto result = fn(forward<decltype(args)>(args)...); os << ... return result; }, forward<Args>(args)...);
But on second thought it seems that bind minimizes the amount of forward
spam, so good job on thinking of that one.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow. This functions shows me that I haven't even started learning modern C++ yet.