You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.6 KiB
C++
57 lines
1.6 KiB
C++
#pragma once
|
|
|
|
#include <rpc/RpcValue.h>
|
|
|
|
#include <functional>
|
|
#include <string>
|
|
#include <tuple>
|
|
#include <unordered_map>
|
|
|
|
class RpcInvoker {
|
|
public:
|
|
template<typename Obj, typename Ret, typename... Args>
|
|
void registerMethod(Obj* instance,
|
|
const std::string& name,
|
|
Ret (Obj::*method)(Args...)) {
|
|
handlers[name] =
|
|
[instance, method](const RpcArgs& args) -> RpcValue {
|
|
auto tuple = readArgs<Args...>(args);
|
|
Ret result = std::apply(
|
|
method, std::tuple_cat(std::make_tuple(instance), tuple));
|
|
|
|
// PoC: считаем, что Ret == int.
|
|
return RpcValue::fromInt(result);
|
|
};
|
|
}
|
|
|
|
RpcValue dispatch(const std::string& method, const RpcArgs& args) const {
|
|
auto it = handlers.find(method);
|
|
if (it == handlers.end()) {
|
|
// PoC: в случае ошибки возвращаем 0.
|
|
return RpcValue::fromInt(0);
|
|
}
|
|
|
|
return it->second(args);
|
|
}
|
|
|
|
private:
|
|
template<typename... Args, std::size_t... I>
|
|
static std::tuple<Args...>
|
|
readArgsImpl(const RpcArgs& args, std::index_sequence<I...>) {
|
|
return std::tuple<Args...>{
|
|
static_cast<Args>(args[I].asInt())...}; // PoC: только int
|
|
}
|
|
|
|
template<typename... Args>
|
|
static std::tuple<Args...> readArgs(const RpcArgs& args) {
|
|
return readArgsImpl<Args...>(
|
|
args, std::make_index_sequence<sizeof...(Args)>{});
|
|
}
|
|
|
|
std::unordered_map<std::string,
|
|
std::function<RpcValue(const RpcArgs&)>>
|
|
handlers;
|
|
};
|
|
|
|
|