命名空间
变体
操作

std::apply

来自 cppreference.cn
< cpp‎ | utility
 
 
 
定义于头文件 <tuple>
template< class F, class Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t );
(since C++17)
(until C++23)
template< class F, tuple-like Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t ) noexcept(/* see below */);
(since C++23)

使用 t 的元素作为参数,调用 可调用 对象 f

给定仅用于阐释目的的函数 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 - 要调用的 可调用 对象
t - 元组,其元素将用作 f 的实参

[编辑] 返回值

f 返回的值。

[编辑] 异常

(无)

(until C++23)
noexcept 规范:  
noexcept(

    noexcept(std::invoke(std::forward<F>(f),
                         std::get<Is>(std::forward<Tuple>(t))...))

)

其中 Is... 表示

(since C++23)

[编辑] 注解

Tuple 不需要是 std::tuple,而可以是任何支持 std::getstd::tuple_size 的类型;特别是,可以使用 std::arraystd::pair

(until C++23)

Tuple 被约束为 tuple-like,即,其中的每个类型都需要是 std::tuple 的特化,或者是另一个对 tuple-like 建模的类型(例如 std::arraystd::pair)。

(since C++23)
特性测试 Std 特性
__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()
{
    // OK
    std::cout << std::apply(add, std::pair(1, 2)) << '\n';
 
    // Error: can't deduce the function type
    // std::cout << std::apply(add_generic, std::make_pair(2.0f, 3.0f)) << '\n'; 
 
    // OK
    std::cout << std::apply(add_lambda, std::pair(2.0f, 3.0f)) << '\n'; 
 
    // advanced example
    std::tuple myTuple{25, "Hello", 9.31f, 'c'};
    std::cout << myTuple << '\n';
}

输出

3
5
[25, Hello, 9.31, c]

[编辑] 参见

创建由实参类型定义的 tuple 对象
(函数模板) [编辑]
创建 转发引用tuple
(函数模板) [编辑]
用实参元组构造对象
(函数模板) [编辑]
(C++17)(C++23)
以给定的实参调用任何 可调用 对象 并可指定返回类型(自 C++23)
(函数模板) [编辑]