in_place — std::in_place 태그

in_place — std::in_place 태그

std::in_place, std::in_place_type, std::in_place_index(및 그 태그 타입)은 "객체를 그 자리에서(in-place) 생성"하라는 신호를 주는 빈 태그 객체들이에요. C++17에서 도입됐어요. <utility> 헤더에 있어요.

std::optional, std::variant, std::any 등이 값을 배치 생성(emplace)할 때 오버로드 선택에 사용해요.

출처: cppreference

본문

// <utility> 헤더, C++17
struct in_place_t { explicit in_place_t() = default; };
inline constexpr std::in_place_t in_place{};

template< class T > struct in_place_type_t;
template< class T > inline constexpr in_place_type_t<T> in_place_type{};

template< std::size_t I > struct in_place_index_t;
template< std::size_t I > inline constexpr in_place_index_t<I> in_place_index{};

사용 예 — optional

#include <optional>
#include <string>

std::optional<std::string> o(std::in_place, 3, 'A');   // "AAA" 배치 생성
std::optional<std::string> o2(std::in_place, "hi");    // "hi"

in_place를 쓰면 임시 객체 없이 생성자를 그대로 호출해 값을 만들어요.

variant에서 — in_place_type/in_place_index

#include <variant>

std::variant<int, std::string> v(std::in_place_type<std::string>, "hello");
// v = "hello" (string 타입 선택)

std::variant<int, std::string> w(std::in_place_index<0>, 42);
// w = 42 (0번째 타입 int 선택)

왜 쓰는가

  • 효율 — 중간 임시 객체를 만들지 않고 목적지에 직접 생성.
  • 명확성 — 어떤 타입/인덱스를 배치 생성할지 모호함 해소.
  • 생성자 직접 호출 — 복사/이동 불가한 타입도 배치 생성 가능.
// 배치 생성으로 복사·이동 없이
std::optional<std::vector<int>> v(std::in_place, {1,2,3});

std::in_place 계열 태그는 optional·variant·any 등에서 값을 "그 자리에 직접 생성"하고 싶을 때, 오버로드 선택을 돕는 도구예요.

더 알아보기 (Learn more)

cppreference