jsonrpcx / json-rpc-cxx

JSON-RPC for modern C++
MIT License
251 stars 44 forks source link

[BUG] - Using GetHandle with a member function using a const qualifier doesn't work #45

Closed phelter closed 1 month ago

phelter commented 5 months ago

Say I have an object:


class Foo {
public:
    int bar() const {return 42;}
};

Using the MethodHandle GetHandle(&Foo::bar, foo) templated function doesn't work because there is no templated function for const functions.

Could you please add the following to your list of templated types:

namespace jsonrpccxx
{
template<typename T, typename ReturnType, typename... ParamTypes>
MethodHandle GetHandle(ReturnType (T::*method)(ParamTypes...) const, const T &instance)
{
    std::function<ReturnType(ParamTypes...)> function = [&instance, method](ParamTypes &&...params) -> ReturnType {
        return (instance.*method)(std::forward<ParamTypes>(params)...);
    };
    return GetHandle(function);
}

template<typename T, typename... ParamTypes>
NotificationHandle GetHandle(void (T::*method)(ParamTypes...) const, const T &instance)
{
    std::function<void(ParamTypes...)> function = [&instance, method](ParamTypes &&...params) -> void {
        return (instance.*method)(std::forward<ParamTypes>(params)...);
    };
    return GetHandle(function);
}
} // namespace jsonrpccxx

This will allow const functions of a const instance to be called as well.

phelter commented 5 months ago

I believe these should be in include/jsonrpccxx/typemapper.hpp

cinemast commented 1 month ago

Thank you, I integrated it.