basic_format_string

basic_format_string (포맷 문자열 래퍼)

이 페이지는 C++20에서 도입된 std::basic_format_string 클래스 템플릿에 대해 다뤄요. 이 타입은 포맷 함수가 사용할 문자열 뷰를 감싸고, 생성 시점에 컴파일 타임 포맷 문자열 검사를 수행해요. C++26부터는 std::dynamic_format이 반환한 문자열에 대해서는 검사가 생략돼요.

출처: cppreference

본문

정의

<format> 헤더에 정의됨
template < class CharT , class ... Args > struct basic_format_string ; (1) (C++20부터)
template < class ... Args > using format_string = basic_format_string < char , std :: type_identity_t < Args > ... > ; (2) (C++20부터)
template < class ... Args > using wformat_string = basic_format_string < wchar_t , std :: type_identity_t < Args > ... > ; (3) (C++20부터)

클래스 템플릿 std::basic_format_string은 포맷 함수에서 사용될 std::basic_string_view를 감싸요. std::basic_format_string의 생성자는 컴파일 타임에 포맷 문자열 검사를 수행해요. 단, 생성자 인자가 std::dynamic_format에 의해 반환된 경우에는 검사하지 않아요 (C++26부터).

멤버 함수

멤버 함수 설명
(constructor) basic_format_string을 생성해요. 인자가 포맷 문자열이 아니면 컴파일 오류가 발생해요. (공개 멤버 함수)
get 감싸고 있는 문자열을 반환해요. (공개 멤버 함수)

std::basic_format_string::basic_format_string

(1)

template < class T > consteval basic_format_string ( const T & s );

(2) (C++26부터)

basic_format_string ( /* dynamic-format-string */ < CharT > s ) noexcept ;

매개변수

s - 포맷 문자열을 나타내는 객체예요. 포맷 문자열은 일반 문자({} 제외)로 구성되며, 이 문자들은 출력에 그대로 복사돼요. 이스케이프 시퀀스 {{}}는 각각 {}로 출력에서 대체돼요. 또한 치환 필드(replacement field)가 포함될 수 있어요. 각 치환 필드는 다음 형식을 가져요:

  • { arg-id (optional) } (1) — 형식 사양 없는 치환 필드

  • { arg-id (optional) : format-spec } (2) — 형식 사양 있는 치환 필드

  • arg-id — 포맷에 사용할 args 중 몇 번째 인자를 사용할지 지정해요. 생략하면 인자들이 순서대로 사용돼요. 포맷 문자열의 arg-id는 모두 있거나 모두 생략되어야 해요. 수동 인덱싱과 자동 인덱싱을 섞으면 오류예요.

  • format-spec — 해당 인자에 대한 std::formatter 전문화에 의해 정의된 형식 사양이에요. }로 시작할 수 없어요.

format-spec의 해석은 다음과 같아요:

  • 기본 타입과 표준 문자열 타입: 표준 형식 사양(standard format specification)으로 해석돼요.
  • chrono 타입: chrono 형식 사양으로 해석돼요.
  • 범위 타입: 범위 형식 사양으로 해석돼요.
  • std::pairstd::tuple: 튜플 형식 사양으로 해석돼요.
  • std::thread::idstd::stacktrace_entry: 각각 thread id 형식 사양과 stacktrace entry 형식 사양을 참고해요.
  • std::basic_stacktrace: 형식 지정자를 허용하지 않아요. (C++23부터)
  • std::filesystem::path: 경로 형식 사양을 참고해요. (C++26부터)
  • 그 외 포맷 가능한 타입: 사용자 정의 formatter 전문화에 의해 결정돼요.

std::basic_format_string::get

constexpr std :: basic_string_view < CharT > get () const noexcept ;

저장된 문자열 뷰를 반환해요.

Notes

별칭 템플릿 format_stringwformat_string은 템플릿 인자 추론을 억제하기 위해 std::type_identity_t를 사용해요. 보통 함수 매개변수로 나타날 때, 그 템플릿 인자는 다른 함수 인자들로부터 추론돼요.

template<class... Args>
std::string format(std::format_string<Args...> fmt, Args&&... args);

auto s = format("{} {}", 1.0, 2);
// Calls format<double, int>. Args are deduced from 1.0, 2
// Due to the use of type_identity_t in format_string, template argument deduction
// does not consider the type of the format string.

Example

이 섹션은 불완전해요. 이유: 예제 없음

Defect reports

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR 적용 대상 게시된 동작 올바른 동작
P2508R1 C++20 이 기능에 사용자에게 보이는 이름이 없었음 basic_format_string 이름이 노출됨

더 알아보기 (Learn more)

cppreference