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から) | |
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), ここで
|
(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() { // 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]
[編集] 関連項目
| (C++11) |
引数型によって定義された型の tuple オブジェクトを生成する(関数テンプレート) |
| (C++11) |
転送参照の tuple を生成する(関数テンプレート) |
| (C++17) |
引数のタプルを使ってオブジェクトを構築する (関数テンプレート) |
| (C++17)(C++23) |
任意の呼び出し可能 (Callable)オブジェクトを所与の引数で呼び出す (戻り値の型を指定することも可能)(C++23以降) (関数テンプレート) |