Abseil utility — apply·in_place
#utility 헤더가 모은 작은 도구들
absl/utility/utility.h는 std 미도착 시기에 필요하던 작은 헬퍼를 모은 곳이다. 대부분 C++17/20에서 std로 들어왔지만 코드 호환을 위해 유지된다.
#include "absl/utility/utility.h"
// 1. apply — tuple 풀어서 함수 호출auto sum = absl::apply([](int a, int b, int c) { return a + b + c; }, std::make_tuple(1, 2, 3)); // 6
// 2. in_place_t / in_place_index_t — emplace tagabsl::optional<std::vector<int>> v(absl::in_place, {1, 2, 3});
// 3. integer_sequence / make_index_sequence — variadic 헬퍼template <typename... Ts>void PrintAll(std::tuple<Ts...> t) { PrintImpl(t, absl::make_index_sequence<sizeof...(Ts)>{});}
// 4. exchange — 값 swap 한 줄T old = absl::exchange(slot, new_value);#absl::apply — tuple 인자 풀기
auto f = [](int a, std::string b, double c) { /* ... */ };auto args = std::make_tuple(1, std::string("x"), 3.14);
absl::apply(f, args); // f(1, "x", 3.14)C++17에 std::apply가 들어왔으므로 그 환경에서는 std 별칭. 일반화된 콜백 처리, decorator, mock framework 내부에서 자주 등장.
// 실용 예 — 호출 정보를 캡처해 나중에 실행struct CallRecord { std::function<void(std::tuple<int, std::string>)> invoker; std::tuple<int, std::string> args;};
void RecordAndReplay(CallRecord r) { absl::apply(r.invoker, r.args);}#in_place_t — 직접 생성
optional/variant/any의 in-place 생성 tag.
absl::optional<std::vector<int>> v(absl::in_place, 10, 0);// vector<int>(10, 0) 직접 생성 — 임시 vector 생성 없음
absl::variant<std::string, int> x(absl::in_place_index<0>, "hello");absl::variant<std::string, int> y(absl::in_place_type<int>, 42);
absl::any a(absl::in_place_type<std::vector<int>>, {1, 2, 3});C++17의 std::in_place, std::in_place_type, std::in_place_index와 동일.
#integer_sequence — variadic 헬퍼
variadic template과 tuple 인덱싱을 함께 다룰 때.
template <typename Tup, std::size_t... I>void PrintImpl(const Tup& t, absl::index_sequence<I...>) { ((std::cout << std::get<I>(t) << " "), ...);}
template <typename... Ts>void Print(const std::tuple<Ts...>& t) { PrintImpl(t, absl::make_index_sequence<sizeof...(Ts)>{});}
Print(std::make_tuple(1, "hello", 3.14)); // 1 hello 3.14C++14 std::make_index_sequence의 polyfill. C++17 fold expression((... , expr))과 결합해 variadic을 깔끔히 처리.
#absl::exchange — 한 줄 swap
class Resource {public: Resource(Resource&& other) noexcept : handle_(absl::exchange(other.handle_, kInvalidHandle)) {}
Resource& operator=(Resource&& other) noexcept { if (this != &other) { std::swap(handle_, other.handle_); } return *this; }};exchange(target, new_value)는 old value를 반환 하고 target에 new_value를 넣는다. move ctor의 표준 관용구.
#absl::launder
C++17 std::launder. union·placement-new·reinterpret_cast 후 aliasing 규칙을 컴파일러에게 알린다.
alignas(T) std::byte storage[sizeof(T)];T* p = new (storage) T();T* clean = absl::launder(p); // strict aliasing safecustom allocator, in-place storage 구현에서만 등장. 일반 코드는 거의 만나지 않는다.
#그 외 작은 helpers
// to_address — fancy pointer를 raw로T* p = std::to_address(it); // iterator → raw pointer (가능한 경우)
// move_if_noexcept — strong exception safety 보장T moved = std::move_if_noexcept(x);과거 Abseil이 제공하던 이 계열 polyfill은 C++17 이후 std로 흡수되면서 제거·ABSL_DEPRECATE_AND_INLINE로 std에 위임됐다. 지금은 std:: 버전을 그대로 쓴다.
#작은 예시 — Variadic logging helper
template <typename... Args>void DebugLog(absl::string_view label, Args&&... args) { auto tup = std::forward_as_tuple(std::forward<Args>(args)...);
auto format = [label](auto&&... xs) { return absl::StrCat(label, ": ", absl::AlphaNum(xs)..., ""); };
LOG(INFO) << absl::apply(format, tup);}
DebugLog("counts", 1, 2, 3, "go"); // "counts: 1 2 3 go"apply + forward_as_tuple 조합으로 가변 인자를 한 번에 forward.
#회피 패턴
// 회피 — boilerplatetemplate <typename Tup, std::size_t... I>auto Call(F f, Tup t, std::index_sequence<I...>) { return f(std::get<I>(t)...);}
// Goodauto r = absl::apply(f, t);// 회피 — optional에 임시 객체 만들고 moveabsl::optional<std::vector<int>> v;v = std::vector<int>(10, 0); // 임시 + move
// Good — in_place로 직접absl::optional<std::vector<int>> v(absl::in_place, 10, 0);#정리
absl::apply— tuple을 함수 인자로 풀어 호출. C++17 std::apply의 polyfill.absl::in_place/in_place_type/in_place_index— optional/variant/any in-place 생성 tag.absl::make_index_sequence+ fold expression — variadic 처리.absl::exchange— move ctor 한 줄 관용구.- 대부분 std에 들어왔으므로 C++17 이상 빌드에서는 std 별칭.
#다음 장 예고
Part 10-01: AbslHashValue — 사용자 타입을 해시 가능하게.
#관련 항목
Abseil Code Review · 56 of 79
- 1 Abseil Code Review — Google production-grade C++ 라이브러리 분석
- 2 Abseil 개요 — Google이 std를 보완한 이유
- 3 Abseil 설계 철학 — std 호환과 추가 기능의 균형
- 4 Abseil 빌드와 의존성 — Bazel vs CMake
- 5 Abseil LTS vs HEAD 릴리스 모델 분석
- 6 Abseil Versioning과 ABI 호환성 정책
- 7 Abseil 매크로 — ABSL_HAVE_*·ABSL_ATTRIBUTE_*
- 8 Abseil ABSL_PREDICT_TRUE/FALSE — branch hint
- 9 absl::LogSeverity — 로그 레벨 타입
- 10 Abseil type_traits — negation·conjunction·void_t
- 11 Abseil Conformance·Policy 분석
- 12 Abseil Memory utilities 분석
- 13 Abseil raw_logging — heap-free 로깅
- 14 Abseil thread_annotations — clang TSA 통합
- 15 absl::Status — exception-free error handling
- 16 absl::StatusOr<T> — 값 또는 에러
- 17 absl status_macros — ASSIGN_OR_RETURN·RETURN_IF_ERROR
- 18 absl::Status payload — 구조화된 에러 컨텍스트
- 19 absl::Status ↔ exception 변환 패턴
- 20 absl::string_view — non-owning 문자열 참조
- 21 absl::string_view 함정 — dangling·c_str·임시 객체
- 22 absl::StrCat — 가변 인자 문자열 연결과 AlphaNum
- 23 absl::StrSplit — Delimiter·Predicate·컨테이너 변환
- 24 absl::StrJoin — 컨테이너 결합과 Formatter
- 25 absl::StrFormat — type-safe printf·FormatSpec
- 26 Abseil ASCII 함수 — locale-free 분류·대소문자 변환
- 27 Abseil Escape — CEscape·HexEscape·Base64
- 28 absl::flat_hash_map — Swiss Table 기반 hash map
- 29 absl::flat_hash_set — set 버전 Swiss Table
- 30 absl::node_hash_map — stable pointer가 필요할 때
- 31 absl::btree_map — sorted·cache-friendly B-tree
- 32 absl::FixedArray — 런타임 크기 stack 배열
- 33 absl::InlinedVector — small buffer optimization
- 34 Abseil Swiss Table internals — control byte·SIMD probing
- 35 absl::Mutex — reader-writer·fairness·deadlock 검출
- 36 absl::Mutex Conditional Critical Section — Await로 cv 없애기
- 37 absl::Notification — once-only signal
- 38 absl::BlockingCounter·Barrier — 다중 thread 조율
- 39 absl::Mutex annotations — clang thread-safety로 race를 컴파일 타임에
- 40 absl::Time·Duration 분석 — 단단한 type
- 41 absl::Time Format·Parse
- 42 absl::CivilTime 분석
- 43 absl::time_zone 분석
- 44 absl::Time mocking — 테스트 친화 시간
- 45 absl::BitGen — 모던 난수 생성기
- 46 Abseil Random Distributions — Uniform·Exponential
- 47 Abseil Mocking Random — 테스트 결정성
- 48 Abseil Random Seeding·Entropy
- 49 absl::int128·uint128 분석
- 50 absl::bits — popcount·countl_zero
- 51 absl::optional vs std::optional
- 52 absl::variant 분석
- 53 absl::span 분석
- 54 absl::any 분석
- 55 absl::compare — three-way 비교
- 56 Abseil utility — apply·in_place
- 57 Abseil AbslHashValue 분석
- 58 Abseil HashState chaining
- 59 Abseil Custom hashable 구현
- 60 Abseil LOG·VLOG·CHECK 분석
- 61 Abseil LogSink 분석
- 62 Abseil LogEntry·structured logging
- 63 Abseil Stack trace·failure_signal_handler
- 64 ABSL_FLAG 정의 분석
- 65 Abseil ParseCommandLine 동작
- 66 Abseil Flag introspection·validation
- 67 Google 스타일의 Abseil 사용 패턴
- 68 Abseil 자주 보는 anti-pattern
- 69 std → absl 마이그레이션 전략
- 70 absl::Cleanup — 함수 종료 시 실행 보장
- 71 Abseil algorithm container 확장 — c_sort·c_find_if·c_count_if
- 72 absl::function_ref와 any_invocable — 함수 객체 전달의 두 축
- 73 absl::bind_front와 Overload — 함수 객체 보조 도구
- 74 absl::Cord — 분산 시스템용 대용량 문자열
- 75 absl::from_chars·SimpleAtoi — 빠른 숫자 변환
- 76 absl::Cord vs std::string — 선택 기준과 메모리 프로파일
- 77 absl::GetStackTrace와 Symbolize — crash 시 readable stack
- 78 absl::ComputeCrc32c — 하드웨어 가속 체크섬
- 79 absl::PeriodicSampler — 적응형 샘플링·jitter 회피
관련 글
absl::compare — three-way 비교
absl::weak_ordering, strong_ordering, partial_ordering — C++20 spaceship의 polyfill과 비교 helper.
같은 시리즈에서 이어 읽기
absl::PeriodicSampler — 적응형 샘플링·jitter 회피
absl::profiling_internal::PeriodicSampler — sampling rate를 동적으로 조정, geometric distribution으로 jitter 회피. 메모리 할당 추적·profiling 인프라의 기반.
같은 시리즈에서 이어 읽기
absl::ComputeCrc32c — 하드웨어 가속 체크섬
absl::ComputeCrc32c — SSE4.2 CRC32, ARM CRC 명령어로 가속된 CRC32C 구현. iSCSI·Btrfs·protobuf에서 표준화된 무결성 검사.
같은 시리즈에서 이어 읽기