C++のput_timeやput_moneyマニピュレータはBoost.Formatと併用できます。

  • put_timeとput_moneyは謎の型を返す単なる関数であり、これらの謎の型は<<演算子で出力できるという決まり。
  • Boost.Formatは<<演算子で出力できる型なら何でも引数に取れる。

そのため、こんなコードも動きます。

#include <ctime>
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
#include <boost/format/group.hpp>
 
int main()
{
  auto t = std::time(nullptr);
  auto tm = std::localtime(&t);
  std::locale l("");
 
  using namespace std;
  using boost::format;
  using boost::io::group;
 
  // cout << put_time(tm, "%c") << endl;
  cout << format("%s") % put_time(tm, "%c") << endl;
  cout << format("%s", l) % put_time(tm, "%c") << endl;
 
  double x = 1234567890;
 
  // cout << put_money(x, false) << endl;
  // cout << showbase << put_money(x, false) << endl;
  cout << format("%s") % put_money(x, false) << endl;
  cout << format("%s", l) % put_money(x, false) << endl;
  cout << format("%#s", l) % put_money(x, false) << endl;
  cout << format("%s", l)
    % group(showbase, put_money(x, false)) << endl;
}

Visual C++ 2010 + Boost 1.50でコンパイルし、日本語版Windowsで実行するとこのような出力になりました。

07/02/12 15:56:18
2012/07/02 15:56:18
1234567890
1,234,567,890
\1,234,567,890
\1,234,567,890

あまり知られていないかもしれませんが、boost::format関数は2番目の引数としてstd::localeを引数に取ります。この書式はput_timeとput_moneyにも影響を及ぼすようです。

また、%#sの#のようなprintf系の書式をiostreamのマニピュレータに翻訳する機能(ユーザー定義型の<<演算子を使用する場合)、iostreamのマニピュレータで書式指定するboost::io::group関数も当然効きました。


スポンサード リンク

この記事のカテゴリ

  • ⇒ put_time/put_moneyとBoost.Format