Namespaces
Variants

std:: apply

From cppreference.net
Utilities library
定义于头文件 <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 ( /* 见下文 */ ) ;
(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::get std::tuple_size 的类型;特别是可以使用 std::array std::pair

(C++23 前)

Tuple 被约束为类元组类型,即要求其中每个类型都必须是 std::tuple 的特化,或是其他满足 tuple-like 概念的类型(例如 std::array std::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()
{
    // 正常
    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 对象
(函数模板)
创建由 转发引用 构成的 tuple
(函数模板)
使用参数元组构造对象
(函数模板)
(C++17) (C++23)
使用给定参数调用任意 Callable 对象 并可指定返回类型 (since C++23)
(函数模板)