最終更新日時(UTC):
が更新

履歴 編集

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>

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: Hello 42 World

バージョン

言語

  • C++23

処理系

参照