std::apply
什么是 std::apply
std::apply 是 C++17 在 <tuple> 头文件中引入的一个工具函数,用来把 tuple(或 pair、array 等类 tuple 类型)的元素"展开"作为参数传递给一个可调用对象。
简单来说,如果你有一个函数 f(a, b, c) 和一个 tuple t = {1, 2, 3},std::apply(f, t) 就等价于调用 f(1, 2, 3)。
在 C++17 之前,要把 tuple 的元素展开为函数参数非常繁琐——需要手写 index_sequence 和模板元编程技巧。std::apply 把这个常见操作封装成了一行代码。
头文件与签名
#include <tuple>
// C++17 签名
template<class F, class Tuple>
constexpr decltype(auto) apply(F&& f, Tuple&& t);
// C++23 起扩展为支持所有 tuple-like 类型,并添加了 noexcept 规范参数说明:
f:任意可调用对象(函数、函数指针、lambda、仿函数、成员函数指针等)t:tuple-like 类型(std::tuple、std::pair、std::array等,任何支持std::get和std::tuple_size的类型)
返回值:f 被调用后的返回值。
基本示例
#include <iostream>
#include <tuple>
#include <string>
#include <array>
#include <utility>
#include <functional>
// ============================
// 示例1:展开 tuple 调用普通函数
// ============================
int add(int a, int b) {
return a + b;
}
void greet(const std::string& name, int age) {
std::cout << "你好," << name << ",你 " << age << " 岁了" << std::endl;
}
void basic_demo() {
// 把 tuple 的元素展开作为函数参数
auto result = std::apply(add, std::make_tuple(3, 4));
std::cout << "3 + 4 = " << result << std::endl; // 7
// 也可以用 pair
auto result2 = std::apply(add, std::make_pair(10, 20));
std::cout << "10 + 20 = " << result2 << std::endl; // 30
// 多参数函数
std::apply(greet, std::make_tuple(std::string("张三"), 25));
}
// ============================
// 示例2:配合 lambda 使用
// ============================
void lambda_demo() {
auto multiply = [](double a, double b, double c) {
return a * b * c;
};
auto args = std::make_tuple(2.0, 3.0, 4.0);
double result = std::apply(multiply, args);
std::cout << "2 * 3 * 4 = " << result << std::endl; // 24
// 带捕获的 lambda
int factor = 10;
auto scaled_add = [factor](int a, int b) {
return (a + b) * factor;
};
auto result2 = std::apply(scaled_add, std::make_tuple(3, 7));
std::cout << "(3 + 7) * 10 = " << result2 << std::endl; // 100
}
// ============================
// 示例3:配合 std::array 使用
// ============================
void array_demo() {
// std::array 也是 tuple-like 类型
std::array<int, 3> arr{10, 20, 30};
auto sum3 = [](int a, int b, int c) {
return a + b + c;
};
int result = std::apply(sum3, arr);
std::cout << "10 + 20 + 30 = " << result << std::endl; // 60
}
// ============================
// 示例4:调用成员函数
// ============================
struct Calculator {
int add(int a, int b) const {
return a + b;
}
};
void member_function_demo() {
Calculator calc;
// 调用成员函数:第一个 tuple 元素是对象(或指针),后面是参数
auto result = std::apply(&Calculator::add, std::make_tuple(calc, 5, 8));
std::cout << "成员函数 add(5, 8) = " << result << std::endl; // 13
// 也可以用指针
auto result2 = std::apply(&Calculator::add, std::make_tuple(&calc, 3, 7));
std::cout << "成员函数 add(3, 7) = " << result2 << std::endl; // 10
}
// ============================
// 示例5:打印 tuple 的所有元素
// ============================
template<typename... Args>
void print_all(const Args&... args) {
// 折叠表达式打印所有参数
((std::cout << args << " "), ...);
std::cout << std::endl;
}
void print_tuple_demo() {
auto t = std::make_tuple(42, "hello", 3.14, 'A');
// 把 tuple 展开传给变参函数
std::apply([](const auto&... args) {
((std::cout << args << " "), ...);
std::cout << std::endl;
}, t);
// 输出: 42 hello 3.14 A
}
int main() {
std::cout << "=== 基本使用 ===" << std::endl;
basic_demo();
std::cout << "\n=== lambda ===" << std::endl;
lambda_demo();
std::cout << "\n=== array ===" << std::endl;
array_demo();
std::cout << "\n=== 成员函数 ===" << std::endl;
member_function_demo();
std::cout << "\n=== 打印 tuple ===" << std::endl;
print_tuple_demo();
return 0;
}进阶用法
#include <iostream>
#include <tuple>
#include <string>
#include <vector>
#include <functional>
#include <memory>
// ============================
// 进阶1:用 apply 实现 make_from_tuple 的效果
// ============================
struct Point {
double x, y, z;
Point(double x, double y, double z) : x(x), y(y), z(z) {
std::cout << "Point(" << x << ", " << y << ", " << z << ")" << std::endl;
}
};
void construct_demo() {
auto args = std::make_tuple(1.0, 2.0, 3.0);
// 用 apply 配合 lambda 构造对象
auto p = std::apply([](auto... args) {
return Point(args...);
}, args);
// C++17 也有 std::make_from_tuple 直接做这件事
// auto p2 = std::make_from_tuple<Point>(args);
}
// ============================
// 进阶2:延迟调用(存储参数,稍后调用)
// ============================
template<typename F, typename... Args>
class DeferredCall {
F func_;
std::tuple<Args...> args_;
public:
DeferredCall(F f, Args... args)
: func_(std::move(f)), args_(std::move(args)...) {}
// 执行延迟调用
decltype(auto) execute() {
return std::apply(func_, args_);
}
};
// 工厂函数
template<typename F, typename... Args>
auto make_deferred(F f, Args... args) {
return DeferredCall<F, Args...>(std::move(f), std::move(args)...);
}
void deferred_demo() {
// 创建延迟调用
auto deferred = make_deferred([](int a, int b) {
std::cout << a << " + " << b << " = " << a + b << std::endl;
return a + b;
}, 10, 20);
std::cout << "准备调用..." << std::endl;
deferred.execute(); // 现在才实际执行
}
// ============================
// 进阶3:结构化绑定产生的值再传给函数
// ============================
std::tuple<std::string, int, double> get_record() {
return {"Alice", 30, 85.5};
}
void process_record(const std::string& name, int age, double score) {
std::cout << name << ", 年龄: " << age << ", 分数: " << score << std::endl;
}
void structured_binding_demo() {
auto record = get_record();
// 直接把 tuple 展开传给处理函数
std::apply(process_record, record);
}
int main() {
std::cout << "=== 构造对象 ===" << std::endl;
construct_demo();
std::cout << "\n=== 延迟调用 ===" << std::endl;
deferred_demo();
std::cout << "\n=== 结构化绑定 ===" << std::endl;
structured_binding_demo();
return 0;
}std::apply 与 std::invoke 的对比
| 特性 | std::apply(f, tuple) | std::invoke(f, args...) |
|---|---|---|
| 参数来源 | tuple/pair/array 展开 | 直接传递各个参数 |
| 用途 | 把打包的参数展开调用 | 统一调用各种可调用对象 |
| 等价调用 | f(get<0>(t), get<1>(t), ...) | f(args...) |
| 头文件 | <tuple> | <functional> |
关键区别:apply 解包 tuple,invoke 不解包。apply 内部就是用 invoke 实现的。
适用场景
- 把 tuple 存储的参数展开传给函数(延迟调用、命令模式)
- 打印或序列化 tuple 的所有元素
- 从 tuple 构造对象(配合构造函数)
- 函数式编程中参数的打包与解包
- 线程池中存储任务参数,执行时用 apply 展开
常见问题
std::apply 能用于重载函数吗?
不能直接用。如果函数有多个重载版本(如 add(int, int) 和 add(double, double)),编译器无法确定你要调用哪个版本。解决方法是用 lambda 包装一层,或者用 static_cast 明确指定函数指针类型。
// 编译错误:add 有重载
// std::apply(add, std::make_tuple(1, 2));
// 解决方案1:lambda 包装
std::apply([](int a, int b) { return add(a, b); }, std::make_tuple(1, 2));
// 解决方案2:static_cast 指定类型
std::apply(static_cast<int(*)(int, int)>(add), std::make_tuple(1, 2));std::apply 能用于模板函数吗?
同样不能直接用,原因类似——模板函数在未实例化前没有确定的类型。用 lambda 包装是最通用的解决方案。
std::apply 和 std::make_from_tuple 有什么区别?
std::apply 调用任意可调用对象,std::make_from_tuple 专门用来用 tuple 参数构造对象(等价于 apply + 构造函数)。
注意事项
- tuple 的元素个数必须和函数参数个数匹配,否则编译错误
std::apply是constexpr的,可以在编译期使用- 不仅支持
std::tuple,也支持std::pair、std::array等 tuple-like 类型 - 对重载函数和模板函数不能直接使用,需要 lambda 包装
- 调用成员函数时,tuple 的第一个元素必须是对象实例(或指针/引用)
编译器支持情况
| 编译器 | 最低支持版本 |
|---|---|
| GCC | 7.0 |
| Clang | 3.9 |
| MSVC | 19.10 (VS 2017) |
总结
std::apply 是 C++17 提供的一个简单但实用的工具函数,解决了"把 tuple 展开为函数参数"这个长期以来需要复杂模板技巧才能完成的操作。它接受一个可调用对象和一个 tuple-like 类型,把 tuple 的每个元素作为独立参数传给可调用对象。这在延迟调用、参数打包/解包、tuple 打印、对象构造等场景下非常有用。配合 C++17 的折叠表达式和结构化绑定,std::apply 让 tuple 相关的编程变得更加自然流畅。