一、介绍
std::apply
是 C++17 中引入的一个函数模板,位于 <tuple>
头文件中。它允许以元组的方式将参数传递给一个可调用对象(函数、函数指针、成员函数指针、函数对象等)。
std::apply
的语法如下:
template <class F, class Tuple>
constexpr decltype(auto) apply(F&& f, Tuple&& t);
其中,F
是可调用对象的类型,Tuple
是一个 std::tuple
或类似的可转换为元组类型的对象。
std::apply
将元组 t
中的元素作为参数传递给可调用对象 f
并执行它。它返回可调用对象的结果。
二、使用
#include <iostream>
#include <tuple>
void print_values(int a, float b, const std::string& c) {
std::cout << "a: " << a << ", b: " << b << ", c: " << c << std::endl;
}
int main() {
std::tuple<int, float, std::string> values(42, 3.14, "Hello");
std::apply(print_values, values);
return 0;
}
在上述示例中,我们定义了一个名为 print_values
的函数,它接受三个参数并打印它们的值。然后我们创建了一个包含三个值的元组 values
。使用 std::apply
,我们将 values
中的元素作为参数传递给 print_values
函数,并打印输出。
输出结果应为:
a: 42, b: 3.14, c: Hello
参考: