使用多个参数调用函数
Call functions with multiple args
如果成员函数有不同数量的args,我可以在容器中存储一个成员函数列表,然后稍后调用它们吗。
我觉得我只是错过了一些小东西,但这就是我所走的路。
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");
}
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?