C++ 使用多个参数调用函数

C++ 使用多个参数调用函数,c++,boost,c++14,variadic-templates,C++,Boost,C++14,Variadic Templates,我是否可以将成员函数列表存储在容器中,然后在以后调用它们(如果它们有不同数量的参数) 我觉得我只是错过了一些小东西,但这就是我所做的 template<typename T> class RPCServer { public: RPCServer(const std::string host, const int port) {} // Store the method pointers template<typename F>

我是否可以将成员函数列表存储在容器中,然后在以后调用它们(如果它们有不同数量的参数)

我觉得我只是错过了一些小东西,但这就是我所做的

template<typename T>
class RPCServer
{
public:
    RPCServer(const std::string host, const int port) {}
        // Store the method pointers
    template<typename F> 
    void register_method(const T discriminant, F func) {
        m_callbacks.emplace_back(discriminant,func);
    }

    template<typename... Args>
    void run(T subject, Args... args) {
        auto func = std::find(std::begin(m_callbacks), std::end(m_callbacks), subject);
        if (func != std::end(m_callbacks)) {
            auto res = std::get<1>(*func)(args...); // This doesn't compile 
        }

    }

    ~RPCServer() = default;
private:
        // Store
    std::vector<std::tuple<T, boost::any>> m_callbacks;
};

class Impl
{
public:
    // RPC methods
    void send_data(std::string data) {}
    int get_details(int input) { return 0; }
};
在这里建立

using namespace std::placeholders;
Impl impl;
RPCServer<std::string> server("localhost",1234);
server.register_method("foo", std::bind(&Impl::send_data, impl, _1));
server.register_method("bar", std::bind(&Impl::get_details, impl, _1));
server.run("foo", "blah"s); // This should call  send_data with 'blah' as a arg
auto result = server.run("bar", 1); // Call get_details passing in 1

如何安全地存储/检索一组成员函数类型。

如何创建适配器模板? 概念验证代码:

#include <iostream>
#include <functional>

template<typename T0, typename... TS> struct FunCaller {
    template<class F> FunCaller(F &&f): f(f) {}
    template<typename... More> T0 operator()(TS &&... as, More &&...) {
            return f(as...);
    }
private:
    std::function<T0(TS...)> f;
};
template<typename T0, typename... TS> inline FunCaller<T0, TS...> funCaller(T0(&&f)(TS...)) { return FunCaller<T0, TS...>(f); }

std::ostream &printSome(std::string const &s1, std::string const &s2) { return std::cout << s1 << ", " << s2 << std::endl; }

int main() {
    auto omg = funCaller(printSome);
    omg("Hello", "world!", "This", "is", "cocaine", "speaking");
}

如果您添加了自动omg2=funcCallerprintSomeMore,并使用不同的args/return,您是否能够将其存储在向量foo={omg,omg2}中?也许可以利用多态性来实现这一点。在这里,在RPCServer::run中构造本地functaller,然后传递参数要简单得多。。。这里:-我在C++03中编写了一个库来实现这一点,其中有一个严肃的概念,即callable的arity总是被一个数字限制,默认情况下是9。您可以使用多种不同类型的函数,并通过几个助手将它们转换为等接口。