命名空间
变体
操作

std::apply

来自 cppreference.cn
< cpp‎ | 工具
 
 
 
定义于头文件 <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 起)

使用 t 的元素作为参数来调用 Callable 对象 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...>) // 仅用于说明
{
    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),
                         std::get<Is>(std::forward<Tuple>(t))...))

)

其中 Is... 表示

(C++23 起)

[编辑] 注解

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

(直至 C++23)

Tuple 被约束为 tuple-like 类型,即其中每个类型都必须是 std::tuple 的特化,或另一个遵循 tuple-like 概念的类型(例如 std::arraystd::pair)。

(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()
{
    // 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)
调用任何带有给定参数的 Callable 对象 并可能指定返回类型(C++23 起)
(函数模板) [编辑]