apply — std::apply
apply — std::apply
std::apply는 튜플(tuple)의 원소들을 함수의 인자로 풀어서 호출하는 함수 템플릿이에요. C++17에서 도입됐어요. <tuple> 헤더에 있어요.
튜플의 각 원소를 함수 인자로 전달해 f(args...)처럼 호출해요.
출처: cppreference
본문
// <tuple> 헤더, C++17
template< class F, class Tuple >
constexpr decltype(auto) apply( F&& f, Tuple&& t );
기본 사용
#include <tuple>
#include <iostream>
int add(int a, int b, int c) { return a + b + c; }
std::tuple<int, int, int> t(1, 2, 3);
int r = std::apply(add, t); // add(1, 2, 3) == 6
람다·멤버 함수
std::apply([](auto... xs) { return (xs + ...); }, std::tuple{1, 2, 3}); // 6
// void 반환도 가능
std::apply([](int a, int b) { std::cout << a << b; }, std::pair{5, 6});
특징
- 튜플·페어뿐 아니라 tuple-like 타입도 지원해요 (C++23부터 더 일반화).
- 인자 수가 함수 매개변수 수와 일치해야 해요.
decltype(auto)반환 — 함수의 반환 타입을 그대로 유지.
// 구조적 활용: 반환값이 pair인 함수를 apply로 처리
auto [min, max] = std::apply([](auto... xs){ return std::minmax({xs...}); },
std::tuple{3, 1, 2});
std::apply는 튜플의 요소들을 개별 인자로 "언패킹"해 함수를 호출할 때 쓰는 표준 도구예요. 제네릭 코드와 결합하면 매우 강력해요.