Skip to content

Instantly share code, notes, and snippets.

@mashiro
Created November 21, 2013 07:50
Show Gist options
  • Save mashiro/7577516 to your computer and use it in GitHub Desktop.
Save mashiro/7577516 to your computer and use it in GitHub Desktop.
#include <future>
#include <memory>
#include <thread>
#include <chrono>
#include <iostream>
namespace miu {
template <typename Derived>
class deferrable
{
public:
typedef std::promise<Derived> promise_type;
typedef std::future<Derived> future_type;
private:
promise_type deferrable_promise_;
public:
deferrable() = default;
deferrable(const deferrable&) = delete;
deferrable& operator=(const deferrable&) = delete;
deferrable(deferrable&& other) = default;
deferrable& operator=(deferrable&& other) = default;
future_type get_future()
{
return deferrable_promise_.get_future();
}
void resolve()
{
promise_type p = std::move(deferrable_promise_);
p.set_value(static_cast<Derived&&>(*this));
}
void reject()
{
reject(std::current_exception());
}
void reject(std::exception_ptr e)
{
promise_type p = std::move(deferrable_promise_);
p.set_exception(e);
}
};
} // miu
struct response : public miu::deferrable<response>
{
std::string method;
std::string url;
int status_code;
std::string body;
};
response::future_type async_request(const std::string& method, const std::string& url)
{
auto res = std::make_shared<response>();
auto f = res->get_future();
std::thread([=]() {
try
{
if (method != "GET")
throw std::runtime_error("GET Only!");
std::this_thread::sleep_for(std::chrono::seconds(1));
res->method = method;
res->url = url;
res->status_code = 200;
res->body = "OK";
res->resolve();
}
catch (...)
{
res->reject();
}
}).detach();
return f;
}
int main()
{
try
{
auto f = async_request("GET", "http://www.yahoo.co.jp");
std::cout << "wait..." << std::endl;
auto res = f.get();
std::cout << res.method << " " << res.url << std::endl;
std::cout << res.status_code << " " << res.body << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment