0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

fmtlib(std::format)でwchar_tやchar16_tを使用する

Posted at

環境

  • fmt-8.1.1
  • VisualStudio2019

fmt::formatでchar以外の文字列をフォーマットする

#include <fmt/xchar.h>
std::wstring  wtext = fmt::format(L"{}",123);
std::u16string  u16text = fmt::format(u"{}",123);
std::u32string  u32text = fmt::format(U"{}",123);

fmt-8.1.1時点ではfmt/xchar.hをインクルードすることでchar以外の型もフォーマットできます。
fmt-7.1.3以前であればfmt/format.hでコンパイルできまます。
フォーマット文字列の型は出力したい文字列の型に合わせてください。
フォーマット文字列がwchar_tなのに引数にcharやchar16_tの文字列を渡すとコンパイルに失敗します。
fmt::formatterの特殊化をすれば使用することは可能です。

ユーザ定義型をchar以外にフォーマットする

struct Point{
	int x,y;
}
template <> struct fmt::formatter<Point, wchar_t> {
	// 書式パース
	template<typename ParseContext>
	constexpr auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
		return ctx.end();
	}
	// フォーマット
	template<typename FormatContext>
	auto format(const Point& point, FormatContext& ctx) -> decltype(ctx.out()) {
		return format_to(ctx.out(), L"({},{})", point.x, point.y);
	}
};

fmt::formatterのテンプレート引数の第2引数に変換先のフォーマットを設定して下さい。
fmtlibのリファレンスだとわかりづらいですが、std::formatterのページに詳しい使用が書いてあります。
cpprefjp
サンプルではParseContextとFormatContextのようにテンプレート化していますが、私の環境では
ParseContextfmt::v8::basic_format_parse_context<wchar_t>
FormatContextfmt::v8::buffer_context<wchar_t>
として呼ばれていました。特に理由がなければテンプレートのままで良いと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?