One of my applications is listening and receiving useful data from a socket. I never want to block. For each payload received, I want to create an object and pass it to the workflow and forget about it until the prototype code is created. But for production code, I want to reduce complexity (my application is large) using the convenient async method. async takes a future made out of a promise. To do this, I need to create a promise for my non-POD object, presented below by the Xxx class. I see no way to do this (see Error in my code example below). Is it appropriate to use async here? If so, how can I build a promise / future object that is more complex than int (all the code examples that I see use int or void):
#include <future> class Xxx //non-POD object { int i; public: Xxx( int i ) : i( i ) {} int GetSquare() { return i * i; } }; int factorial( std::future< Xxx > f ) { int res = 1; auto xxx = f.get(); for( int i = xxx.GetSquare(); i > 1; i-- ) { res *= i; } return res; } int _tmain( int argc, _TCHAR* argv[] ) { Xxx xxx( 2 ); // 2 represents one payload from the socket std::promise< Xxx > p; // error: no appropriate default constructor available std::future< Xxx > f = p.get_future(); std::future< int > fu = std::async( factorial, std::move( f ) ); p.set_value( xxx ); fu.wait(); return 0; }
source share