GeezerVison is showing cpprefjp.github.io — std::basic_format_string::コンストラクタ - cpprefjp C++日本語リファレンス
最終更新日時:
2026年05月15日 14時22分58秒 (JST)
Akira Takahashi
が更新
履歴
編集
function
<format>
std:: basic_format_string:: コンストラクタ (C++23)
template < class T >
consteval
basic_format_string ( const T & s ); // (1) C++23
constexpr
basic_format_string ( dynamic-format-string < charT > s ) noexcept ; // (2) C++26
概要
basic_format_stringオブジェクトを構築する。
(1) : コンパイル時の書式文字列を受け取る
(2) : 実行時の書式文字列を受け取る
テンプレートパラメータ制約
効果
メンバ変数としてbasic_string_view<charT> str;が定義されるとして、str(s)で初期化する。
備考
この関数の呼び出しは、strがargsの書式文字列であるような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 > ... > ;
}
バージョン
言語
処理系
参照