如何在C++中实现类似JavaScript使用rest/spread操作符的executor函数
C++ executor 函数实现方案
你可以通过C可变参数模板配合完美转发实现与目标JS代码完全一致的功能,最低兼容C11标准:
基础实现(C++14及以上)
#include <utility> template <typename Func, typename... Args> decltype(auto) executor(Func&& foo, Args&&... args) { return std::forward<Func>(foo)(std::forward<Args>(args)...); }
语法对应说明
typename... Args对应JS的...argsrest参数,用于声明任意长度、任意类型的参数包Args&&... args为万能引用,可同时匹配左值、右值参数,避免多余拷贝std::forward<Args>(args)...对应JS的...argsspread操作符,展开参数包的同时保留每个参数原本的值类型(左值/右值)传递给目标函数std::forward<Func>(foo)保留传入可调用对象的原始类型,支持普通函数、lambda、函数对象、std::function等所有可调用类型- 如果你需要兼容C++11,可改用后置返回值写法:
// C++11 兼容版本 #include <utility> template <typename Func, typename... Args> auto executor(Func&& foo, Args&&... args) -> decltype(std::forward<Func>(foo)(std::forward<Args>(args)...)) { return std::forward<Func>(foo)(std::forward<Args>(args)...); }
使用示例
#include <iostream> #include <string> // 测试函数1:两数求和 int add(int a, int b) { return a + b; } // 测试函数2:打印字符串 void print_str(const std::string& content) { std::cout << content << "\n"; } int main() { // 调用两数求和 std::cout << executor(add, 2, 3) << "\n"; // 输出 5 // 调用打印函数 executor(print_str, "测试执行成功"); // 输出 测试执行成功 // 调用lambda executor([](int x, int y, int z) { std::cout << x + y + z << "\n"; }, 1, 2, 3); // 输出6 return 0; }
内容的提问来源于stack exchange,提问作者7ice
相关产品推荐
相关产品推荐

