GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::basic_format_string - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. format
  3. basic_format_string

最終更新日時: 2026年09月17日 11時50分52秒 (JST)
Akira Takahashi が更新

履歴 編集

class
<format>

std::basic_format_string(C++23)

namespace std {
  template <class charT, class... Args>
  struct basic_format_string;

  template <class... Args>
  using format_string = basic_format_string<char, type_identity_t<Args>...>;

  template <class... Args>
  using wformat_string = basic_format_string<wchar_t, type_identity_t<Args>...>;
}

概要

basic_format_stringクラスは、コンパイル時の書式文字列を表すクラスである。

C++20までは説明専用クラスbasic-format-stringとして定義されていたが、C++23からはユーザーが利用できる正式な機能として定義される。

このクラスは、書式文字列のコンパイル時チェックを行う。

auto str = std::format("{:d}", "I am not a number"); // コンパイルエラー!
                                                     // 書式文字列は「d」で整数を要求しているが、引数として文字列が渡された

このクラスのコンストラクタは、パラメータの書式文字列と、クラステンプレートパラメータのArgs...を照合し、

  • 書式文字列の型チェック
  • 開きカッコと閉じカッコの一致
  • その他、型ごとに許可されたオプションが正しいか

などをチェックする。

C++23で説明専用クラスでなく正式な機能として定義されたことにより、以下のように書式化を含むロギングなどをユーザーが定義できるようになる。

template <typename... Args>
void log(std::format_string<Args...> s, Args&&... args) {
  if (logging_enabled) {
    log_raw(std::format(s, std::forward<Args>(args)...));
  }
}

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++23
get 書式文字列を取得する C++23

例

#include <iostream>
#include <format>
#include <chrono>
#include <utility>

thread_local bool logging_enabled = true;

// 現在時刻付きで、文字列フォーマットしてログ出力する
template <typename... Args>
void log(std::format_string<Args...> s, Args&&... args) {
  if (!logging_enabled) {
    return;
  }

  namespace chrono = std::chrono;
  auto now = chrono::floor<chrono::seconds>(chrono::system_clock::now());
  std::cout << std::format("{}: {}",
    chrono::zoned_time{"Asia/Tokyo", now},
    std::format(s, std::forward<Args>(args)...)
  ) << std::endl;
}

int main()
{
  log("Hello {} World", 42);
}

出力例

2023-02-06 10:46:53 JST: Hello 42 World

バージョン

言語

  • C++23

処理系

  • Clang: ??
  • GCC: 13.1 ✅
  • Visual C++: ??

参照

  • P2508R1 Expose std::basic-format-string<charT, Args...>
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.