Skip to content

Instantly share code, notes, and snippets.

@goldshtn
Last active May 8, 2018 01:24
Show Gist options
  • Save goldshtn/7433212 to your computer and use it in GitHub Desktop.
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…
#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;
});
}
@pmalek
Copy link

pmalek commented Aug 15, 2015

Simply... wow...
@goldshtn: can you show a usage of that function?

@jepio
Copy link

jepio commented Aug 16, 2015

@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 of bind 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