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부터) | |
호출 가능(Callable) 객체 f를 t의 요소들을 인자로 사용하여 호출합니다.
다음과 같이 정의된 설명 전용 함수 apply-impl가 주어집니다:
template<class F,class Tuple, std::size_t... I>
constexpr decltype(auto)
apply-impl(F&& f, Tuple&& t, std::index_sequence<I...>) // exposition only
{
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() { // 정상 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
객체를 생성함
(함수 템플릿) |
|
(C++11)
|
전달 참조
의
tuple
을 생성함
(함수 템플릿) |
|
(C++17)
|
인자들의 튜플로 객체를 생성함
(함수 템플릿) |
|
(C++17)
(C++23)
|
주어진 인자들로
Callable
객체를 호출함
(반환 타입 지정 가능)
(C++23부터)
(함수 템플릿) |