CKTIS / C++
std::apply: calling a function with tuple elements
std::apply expands a tuple-like object into the arguments of a callable and returns the result of that invocation.
Version: C++23
Syntax
template<class F, tuple-like Tuple>
constexpr decltype(auto) apply(F&& function, Tuple&& tuple);
// tuple-like is an exposition-only C++23 library constraintstd::apply from <tuple> performs std::invoke(f, get<0>(t), ..., get<N-1>(t)). In C++23, Tuple meets the library's exposition-only tuple-like constraint; supported standard tuple-like types include std::tuple, std::pair, and std::array. Merely adding custom tuple_size and get specializations does not guarantee support for an arbitrary user-defined type. The exact invocation result, including void, is returned.
Use it when arguments are already packed in a tuple. Expansion follows a size known at compile time rather than a runtime loop. Element value categories are forwarded according to the value category of the tuple argument.
All elements must form a valid call to f; a wrong count or type is a compile-time error. Moving the tuple can pass its elements as rvalues. Exceptions from the invoked function propagate unchanged.
Examples
#include <iostream>
#include <tuple>
int main() {
const auto values = std::tuple{2, 5};
const int sum = std::apply([](int left, int right) { return left + right; }, values);
std::cout << sum << '\n';
}
Result
7
std::apply → 7