Created
November 12, 2013 11:13
-
-
Save mashiro/7429275 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <future> | |
#include <memory> | |
#include <iostream> | |
#include <boost/lexical_cast.hpp> | |
template <typename T> | |
class deferred | |
{ | |
public: | |
typedef deferred deferred_type; | |
typedef T deferred_value_type; | |
typedef std::promise<deferred_value_type> promise_type; | |
typedef std::future<deferred_value_type> future_type; | |
private: | |
promise_type deferred_promise_; | |
public: | |
deferred() = default; | |
deferred(const deferred&) = delete; | |
deferred& operator=(const deferred&) = delete; | |
future_type future() | |
{ | |
return deferred_promise_.get_future(); | |
} | |
void resolve() | |
{ | |
promise_type&& p = std::move(deferred_promise_); | |
p.set_value(static_cast<deferred_value_type&&>(*this)); | |
} | |
void reject() | |
{ | |
reject(std::current_exception()); | |
} | |
void reject(std::exception_ptr e) | |
{ | |
promise_type&& p = std::move(deferred_promise_); | |
p.set_exception(e); | |
} | |
}; | |
template <typename T> | |
class deferred_value : public deferred<deferred_value<T>> | |
{ | |
public: | |
typedef T value_type; | |
private: | |
value_type value_; | |
public: | |
deferred_value() = default; | |
deferred_value(deferred_value&& other) | |
: value_(std::move(other.value_)) | |
{} | |
void resolve(const value_type& value) | |
{ | |
value_ = value; | |
deferred_value::deferred_type::resolve(); | |
} | |
const value_type& value() const | |
{ | |
return value_; | |
} | |
}; | |
typedef deferred_value<int> result_t; | |
result_t::future_type to_int(const char* input) | |
{ | |
auto ret = std::make_shared<result_t>(); | |
std::async(std::launch::async, | |
[=]() { | |
try | |
{ | |
int v = boost::lexical_cast<int>(input); | |
ret->resolve(v); | |
} | |
catch (...) | |
{ | |
ret->reject(); | |
} | |
}); | |
return ret->future(); | |
} | |
int main(int argc, char** argv) | |
{ | |
if (argc != 2) | |
{ | |
std::cout << "to_int <input>" << std::endl; | |
return -1; | |
} | |
try | |
{ | |
auto f = to_int(argv[1]); | |
auto ret = f.get(); | |
std::cout << ret.value() << 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