#c++ format vformatサンプル
format: コンパイル時書式文字列
vformat: 実行時の書式文字列
#include <iostream>
#include <sstream>
#include <format>
#include <locale>
using namespace std;
//カスタムロケール
class comma_numpunct : public numpunct<char> {
protected:
virtual char do_decimal_point() const override {
return ',';
}
virtual char do_thousands_sep() const override {
return '.';
}
virtual string do_grouping() const override {
return "\003";
}
};
/*
* 最小構成
*/
void format_sample0() {
cout << format("{}{} {}{}", "Hello", ',', "C++", 0) << endl;
}
/*
* 型明示
*/
void format_sample1() {
format_string<string_view,char,string,int> fmt = "{}{} {}{}";
string s1 = format(fmt, string_view("Hello"), ',', string("C++"),1);
cout << s1 << endl;
}
/**
型推論は出来ない
void format_sample1_1() {
auto fmt = "{}{} {}{}";
string s1 = format(fmt, string_view("Hello"), ',', string("C++"), 1);
cout << s1 << endl;
}
*/
/**
ロケール設定あり
*/
void format_sample2(const locale&loc) {
double d1 = 123456.78901;
cout << format(loc,"{}\t{:L}", d1,d1) << endl;
}
/******************************************************
文字フォーマットが実行時に決まる場合
vformat
************/
template<typename... Args>
void vprintln(const string fmt, Args&&... args)
{
cout << vformat(fmt, make_format_args(args...)) << endl;
}
/**
最小構成
*/
void vformat_sample1() {
vprintln("{}{} {}{}", "Hello", ',', "C++", -1 + 2 * 3 * 4);
}
/**
オプション書式
https://cpprefjp.github.io/reference/format/format.html
[[fill] align] [sign] ['#'] ['0'] [width] ['.' precision] ['L'] [type]
*/
int main(){
format_sample0();
format_sample1();
locale loc1("en-US.UTF-8");
locale loc2(locale::classic(), new comma_numpunct());
format_sample2(loc1);
format_sample2(loc2);
vformat_sample1();
return 0;
}