jeudi 29 décembre 2016

Returning std::future (or std::shared_future etc) from a method

I am trying to implement a generic RPC invoker to return some sort of a future to the calling service and fail to understand the C++ semantics behind the use of std::future and std::shared_future. So far I have produced the following code, which won't compile because futures cannot be copied, and I cannot figure our how to move further from here. This same concept works perfectly well when implemented with CompletableFuture of netty.io promises in Java.

#include <future>
#include <string>

class Invoker {
    public:
        template<typename RQ, typename RS> std::future<RS> invoke(const RQ& request, RS& inst) const {
            std::promise<RS> promise;
            promise.set_value(inst); // FIXME just for the example
            return promise.get_future();
        }
};

struct GetRateRequest {
        std::string symbol;
};

struct GetRateResponse {
        double rate;
};

class FxRateService {
        const Invoker* invoker;

    public:
        FxRateService(const Invoker* invoker) {
            this->invoker = invoker;
        }

        std::future<double> getRate(std::string symbol) {
            GetRateRequest request = { .symbol = symbol };
            GetRateResponse tmpl = { .rate = 0.0 };
            auto fut = invoker->invoke<GetRateRequest, GetRateResponse>(request, tmpl);

            std::promise<double> res;
            // FIXME: set in async when future is ready
            res.set_value(fut.get().rate);
            return res.get_future();
        }

        double getRateSync(std::string symbol) {
            return getRate(symbol).get();
        }
};

So what am I doing wrong with returning the futures, what should I return instead and how to get the corresponding type conversion?

Aucun commentaire:

Enregistrer un commentaire