Thursday, October 27, 2016

Transform a type into awaitable by Adapter or pass trhough


#include "stdafx.h"

#include <experimental\coroutine>
#include <iostream>
#include <string>
#include <future>
#include <thread>

using namespace std;
using namespace std::experimental;

template<typename T>
struct await_adapter
{
 T const& t_;
 bool await_readY() const;
 void await_suspend(std::experimental::coroutine_handle<> h) const;
 auto await_resume() const;
};

template<typename T>
class IAsyncOperation 
{

};

template<typename T>
await_adapter<IAsyncOperation<T>> operator co_await(IAsyncOperation<T> const& async)
{
 return async;
};

struct pass_through
{
 int result;
 bool await_ready() { return true; }
 void await_suspend(std::experimental::coroutine_handle<> h) {};
 auto await_resume() { return result; }
};

struct value
{
 int result;
};

pass_through operator co_await(value v)  // overload operator to make awaitable
{
 return{ v.result };
};

void test()
{
 auto i = co_await pass_through{ 123 };
 auto j = co_await value{ 456 };
}

int main()
{
 cout << "main thread id:" << std::this_thread::get_id() <<endl;
 test();
 //cout << r.get() << endl; //get causes return, no SM setup
 
 std::string s;
 getline(cin, s);
    return 0;
}


No comments:

Post a Comment