Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <future>
- #include <iostream>
- #include <string>
- #include <sstream>
- template <typename T> class AsyncResult {
- private:
- std::future<T> fut;
- public:
- #ifdef __BLOCKS__
- AsyncResult(BlockWrapper<T>&& bw) : fut(std::async(std::launch::async, bw)) {}
- #else
- AsyncResult(std::function<T()>&& f) : fut(std::async(std::launch::async, f)) {}
- #endif
- AsyncResult(AsyncResult&& r) : fut(std::move(r.fut)) {}
- operator T() { return fut.get(); }
- T operator+(T n);
- };
- #ifdef __BLOCKS__
- #define LAMBDA(x) BlockWrapper<decltype(x)>(^{ return x; })
- #else
- #define LAMBDA(x) [=]()->decltype(x){ return x; }
- #endif
- #define ASYNC(x) AsyncResult<decltype(x)>(LAMBDA(x))
- template <typename T> T AsyncResult<T>::operator+(T n) { return fut.get() + n; }
- template <> std::string AsyncResult<std::string>::operator+(std::string n) {
- std::stringstream ss;
- ss << fut.get() << n;
- return ss.str();
- }
- std::string download(const std::string& url) {
- if (url == "BBB")
- sleep(20);
- else
- sleep(15);
- return url;
- }
- void process(const std::string& s) {
- std::cout << s << std::endl;
- }
- int main(void) {
- auto s1 = ASYNC(download("AAA"));
- auto s2 = ASYNC(download("BBB"));
- process(s1 + s2);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement