std::apply
| 定义于头文件 <tuple>
|
||
template< class F, class Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t );
|
(C++17 起) (C++23 前) |
|
template< class F, tuple-like Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t ) noexcept(/* see below */);
|
(C++23 起) | |
调用可调用 (Callable) 对象 f,以 t 的元素作为参数。
给定仅用于阐述的函数 apply-impl 定义如下:
template<class F,class Tuple, std::size_t... I>
constexpr decltype(auto)
apply-impl(F&& f, Tuple&& t, std::index_sequence<I...>) // exposition only
{
return INVOKE(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...);
}
效果等价于:
return apply-impl(std::forward<F>(f), std::forward<Tuple>(t),
std::make_index_sequence<
std::tuple_size_v<std::decay_t<Tuple>>>{});
。
参数
| f | - | 将被调用的 Callable 对象 |
| t | - | 其元素将用作 f 参数的元组 |
返回值
f 返回的值。
异常
|
(无) |
(C++23 前) |
|
noexcept
规范:
noexcept
(
noexcept
(
std::
invoke
(
std::
forward
<
F
>
(
f
)
,
其中
|
(C++23 起) |
注释
|
|
(C++23 前) |
|
|
(C++23 起) |
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_apply
|
201603L
|
(C++17) |
std::apply
|
示例
#include <iostream> #include <tuple> #include <utility> int add(int first, int second) { return first + second; } template<typename T> T add_generic(T first, T second) { return first + second; } auto add_lambda = [](auto first, auto second) { return first + second; }; template<typename... Ts> std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple) { std::apply ( [&os](Ts const&... tupleArgs) { os << '['; std::size_t n{0}; ((os << tupleArgs << (++n != sizeof...(Ts) ? ", " : "")), ...); os << ']'; }, theTuple ); return os; } int main() { // 正常 std::cout << std::apply(add, std::pair(1, 2)) << '\n'; // 错误:无法推导函数类型 // std::cout << std::apply(add_generic, std::make_pair(2.0f, 3.0f)) << '\n'; // 正常 std::cout << std::apply(add_lambda, std::pair(2.0f, 3.0f)) << '\n'; // 高级示例 std::tuple myTuple{25, "Hello", 9.31f, 'c'}; std::cout << myTuple << '\n'; }
输出:
3 5 [25, Hello, 9.31, c]
参见
|
(C++11)
|
创建由参数类型定义的
tuple
对象
(函数模板) |
|
(C++11)
|
创建由
转发引用
构成的
tuple
(函数模板) |
|
(C++17)
|
使用参数元组构造对象
(函数模板) |
|
(C++17)
(C++23)
|
使用给定参数调用任意
Callable
对象
并可指定返回类型
(since C++23)
(函数模板) |