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

履歴 編集

function
<format>

std::basic_format_string::コンストラクタ(C++23)

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

概要

basic_format_stringオブジェクトを構築する。

テンプレートパラメータ制約

効果

メンバ変数としてbasic_string_view<charT> str;が定義されるとして、str(s)で初期化する。

備考

  • この関数の呼び出しは、strargsの書式文字列であるようなArgs型のargsが存在しない限り、コア定数式ではない
    • 意味 : 書式文字列が引数列argsと合わせて正しくなければ、定数式評価 (consteval) が実行できずコンパイルエラーとなる
    • 以下のようなコードはコンパイルエラーとなる:
      int main() {
        auto str = std::format("{:d}", "I am not a number"); // コンパイルエラー!型が合わない
      }
      

実装例

// 書式文字列のチェック
template <class CharT, class... Args>
consteval void fmt_checker(std::basic_string_view<CharT> str)
{
  // …

  if (/*カッコの開き・閉じが一致しない場合*/) {
    throw "invalid brackets"; // throw式は定数式で実行できないため、
                              // このパスを通ったらコンパイルエラーになる
  }

  // …

  if (/*型が合わない時*/) {
    throw "invalid type specifier";
  }

  // …
}

namespace std {
  template <class CharT, class... Args>
  struct basic_format_string {
    std::basic_string_view<CharT> str;

    template <class T>
      requires std::convertible_to<const T&, std::basic_string_view<charT>>
    consteval basic_format_string(const T& s)
      : str(s)
    {
      fmt_checker<CharT, Args...>(str);
    }
  };

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

バージョン

言語

  • C++23

処理系

参照