名稱空間
變體
操作

std::apply

來自 cppreference.com
< 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 起)
(函式模板) [編輯]