From 6a9cdf5272a230bfe82b0d5a9bf59869743ac5d5 Mon Sep 17 00:00:00 2001 From: Alexander Zaitsev Date: Fri, 1 May 2020 01:48:20 +0300 Subject: [PATCH] Add possibility to register void methods as a JSON-RPC message --- include/jsonrpccxx/typemapper.hpp | 17 +++++++++++++++++ test/typemapper.cpp | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/include/jsonrpccxx/typemapper.hpp b/include/jsonrpccxx/typemapper.hpp index 57ad248..9ea7e13 100644 --- a/include/jsonrpccxx/typemapper.hpp +++ b/include/jsonrpccxx/typemapper.hpp @@ -24,6 +24,7 @@ namespace jsonrpccxx { constexpr json::value_t GetType(type) { return json::value_t::object; } + constexpr json::value_t GetType(type) { return json::value_t::null; } constexpr json::value_t GetType(type) { return json::value_t::string; } constexpr json::value_t GetType(type) { return json::value_t::boolean; } constexpr json::value_t GetType(type) { return json::value_t::number_float; } @@ -148,6 +149,22 @@ namespace jsonrpccxx { // // Mapping for classes // + template + MethodHandle methodHandle(ReturnType (T::*method)(ParamTypes...), T &instance) { + std::function function = [&instance, method](ParamTypes &&... params) -> ReturnType { + return (instance.*method)(std::forward(params)...); + }; + return methodHandle(function); + } + + template + NotificationHandle notificationHandle(void (T::*method)(ParamTypes...), T &instance) { + std::function function = [&instance, method](ParamTypes &&... params) -> void { + return (instance.*method)(std::forward(params)...); + }; + return notificationHandle(function); + } + template MethodHandle GetHandle(ReturnType (T::*method)(ParamTypes...), T &instance) { std::function function = [&instance, method](ParamTypes &&... params) -> ReturnType { diff --git a/test/typemapper.cpp b/test/typemapper.cpp index 1bd65ab..4abbe7e 100644 --- a/test/typemapper.cpp +++ b/test/typemapper.cpp @@ -43,6 +43,18 @@ TEST_CASE("test class member binding", TEST_MODULE) { CHECK(notifyResult == "Hello world: someone"); } +TEST_CASE("test class member explicit binding", TEST_MODULE) { + SomeClass instance; + MethodHandle mh = methodHandle(&SomeClass::add, instance); + CHECK(mh(R"([3, 4])"_json) == 7); + + notifyResult = ""; + NotificationHandle mh2 = notificationHandle(&SomeClass::notify, instance); + CHECK(notifyResult.empty()); + mh2(R"(["someone"])"_json); + CHECK(notifyResult == "Hello world: someone"); +} + TEST_CASE("test incorrect params", TEST_MODULE) { SomeClass instance; MethodHandle mh = GetHandle(&SomeClass::add, instance);