Namespaces
Variants

std:: format

From cppreference.net
헤더에 정의됨 <format>
template < class ... Args >
std:: string format ( std:: format_string < Args... > fmt, Args && ... args ) ;
(1) (C++20부터)
template < class ... Args >
std:: wstring format ( std:: wformat_string < Args... > fmt, Args && ... args ) ;
(2) (C++20부터)
template < class ... Args >

std:: string format ( const std:: locale & loc,

std:: format_string < Args... > fmt, Args && ... args ) ;
(3) (C++20부터)
template < class ... Args >

std:: wstring format ( const std:: locale & loc,

std:: wformat_string < Args... > fmt, Args && ... args ) ;
(4) (C++20부터)

형식 문자열 fmt 에 따라 args 를 포맷하고 결과를 문자열로 반환합니다. 존재하는 경우, loc 은 로케일별 포맷팅에 사용됩니다.

1) 다음과 동일함 return std:: vformat ( fmt. get ( ) , std:: make_format_args ( args... ) ) ; .
2) 다음에 해당함 return std:: vformat ( fmt. get ( ) , std:: make_wformat_args ( args... ) ) ; .
3) 다음에 해당함 return std:: vformat ( loc, fmt. get ( ) , std:: make_format_args ( args... ) ) ; .
4) 다음에 해당함 return std:: vformat ( loc, fmt. get ( ) , std:: make_wformat_args ( args... ) ) ; .

형식 문자열 fmt 는 컴파일 타임에 검사됩니다 (단, std::runtime_format 의 결과로 초기화된 경우는 제외) (C++26부터) . 컴파일 타임에 형식 문자열이 포맷할 인수의 타입에 대해 유효하지 않은 것으로 판단되면 컴파일 오류가 발생합니다.

다음 요구 사항들은 Args 내의 각 타입 T 에 적용되며, 여기서 CharT char 인 경우 오버로드 (1,3) 에 해당하고, wchar_t 인 경우 오버로드 (2,4) 에 해당합니다:

목차

매개변수

fmt - 포맷 문자열을 나타내는 객체. 포맷 문자열은 다음으로 구성됩니다:
  • 일반 문자( { } 제외), 출력에 변경 없이 복사됩니다,
  • 이스케이프 시퀀스 { { } } , 출력에서 각각 { } 로 대체됩니다, 그리고
  • 치환 필드.

각 치환 필드는 다음 형식을 가집니다:

{ arg-id (optional) } (1)
{ arg-id (optional) : format-spec } (2)
1) 포맷 명세가 없는 치환 필드
2) 포맷 명세가 있는 치환 필드
arg-id - 포맷팅에 사용될 인수의 args 내 인덱스를 지정합니다; 생략된 경우 인수는 순서대로 사용됩니다.

포맷 문자열 내 arg-id 들은 모두 존재하거나 모두 생략되어야 합니다. 수동 및 자동 인덱싱을 혼합하는 것은 오류입니다.

format-spec - 해당 인수에 대한 std::formatter 특수화에 의해 정의된 포맷 명세. } 로 시작할 수 없습니다.

(C++23부터)
(C++26부터)
  • 다른 포맷 가능 타입의 경우, 포맷 명세는 사용자 정의 formatter 특수화에 의해 결정됩니다.
args... - 포맷팅될 인수들
loc - std::locale 지역별 포맷팅에 사용될 로케일

반환값

형식화된 결과를 담고 있는 문자열 객체.

예외

할당 실패 시 std::bad_alloc 을 발생시킵니다. 또한 모든 포매터(formatter)에서 발생한 예외를 전파합니다.

참고 사항

형식 문자열이 요구하는 것보다 더 많은 인수를 제공하는 것은 오류가 아닙니다:

std::format("{} {}!", "Hello", "world", "something"); // OK, "Hello world!"를 생성합니다

형식 문자열이 상수 표현식이 아닌 경우 오류입니다 std::runtime_format 의 결과로 초기화된 경우가 아니면 (C++26부터) . std::vformat 에는 이 요구 사항이 적용되지 않습니다.

std::string f1(std::string_view runtime_format_string)
{
    // return std::format(runtime_format_string, "x", 42); // 오류
    char v1[] = "x";
    int v2 = 42;
    return std::vformat(runtime_format_string, std::make_format_args(v1, v2)); // 정상
}
std::string f2(std::string_view runtime_format_string)
{
    return std::format(std::runtime_format(runtime_format_string), "x", 42); // 정상 (C++26)
}

예제

#include <format>
#include <iostream>
#include <set>
#include <string>
#include <string_view>
template<typename... Args>
std::string dyna_print(std::string_view rt_fmt_str, Args&&... args)
{
    return std::vformat(rt_fmt_str, std::make_format_args(args...));
}
int main()
{
#ifdef __cpp_lib_format_ranges
        const std::set<std::string_view> continents 
        {
            "Africa",   "America",      "Antarctica",   
            "Asia",     "Australia",    "Europe"
        };
        std::cout << std::format("Hello {}!\n", continents);
#else
        std::cout << std::format("Hello {}!\n", "continents");
#endif
    std::string fmt;
    for (int i{}; i != 3; ++i)
    {
        fmt += "{} "; // 포맷팅 문자열 구성
        std::cout << fmt << " : ";
        std::cout << dyna_print(fmt, "alpha", 'Z', 3.14, "unused");
        std::cout << '\n';
    }
}

가능한 출력:

Hello {"Africa", "America", "Antarctica", "Asia", "Australia", "Europe"}!
{}  : alpha
{} {}  : alpha Z
{} {} {}  : alpha Z 3.14

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
P2216R3 C++20 잘못된 형식 문자열에 대해 std::format_error 를 발생시킴 잘못된 형식 문자열은 컴파일 타임 오류를 발생시킴
P2418R2 C++20 const-usable도 아니고 복사 가능하지도 않은 객체
(예: 생성기형 객체)는 포맷팅 불가능
이러한 객체의 포맷팅 허용
P2508R1 C++20 이 기능에 대한 사용자 가시적 이름이 없음 basic_format_string 이름이 노출됨

참고 항목

(C++20)
출력 반복자를 통해 인수의 형식화된 표현을 기록합니다
(함수 템플릿)
출력 반복자를 통해 인수의 형식화된 표현을 기록하며, 지정된 크기를 초과하지 않음
(함수 템플릿)