c++ - 调用具有多个参数的函数

标签 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> 
    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");
}

关于c++ - 调用具有多个参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522734/

相关文章:

c++ - 无法推断出作为函数的模板参数

c++ - Boost mutex 在等待线程关闭时抛出错误

c++ - 当我将元素类型存储在另一个字符串 vector 中时,如何打印一个 boost::any vector ?

c++ - boost locale c++ - 了解基础知识

c++ - 嵌套或继承的类型特征

c++ - 更改保持原始指针指向其字段的对象的地址

python - pybind11 模块目录

c++ - clang++ 内存清理器报告未初始化值的使用

c++ - 如何在 gcc 中为未使用的 lambda 表达式启用警告?

c++ - 如果模板参数是另一个模板的某个实例,则类型特征测试