Sprout.IO
Sprout に IO を扱うライブラリが追加されたのでちょっと触ってみた。
ちなみにまだ Input はないらしい。
詳細については id:boleros さんの記事を参照して下さい。
[ソース]
#include <sprout/string.hpp> #include <sprout/io.hpp> #include <iostream> struct person{ sprout::string<16> name; std::size_t age; }; template<typename L, typename R> constexpr auto operator <<(sprout::io::format_expression<L, R> const& os, person const& p) ->decltype(os << p.name << ':' << p.age){ return os << p.name << ':' << p.age; } int main(){ namespace io = sprout::io; constexpr auto v = io::output<16>(io::root << "test" << 42); static_assert(v == "test42", ""); std::cout << v << std::endl; // ユーザ定義型で出力 constexpr person homu{ sprout::to_string("homu"), 14 }; constexpr auto v2 = io::output<16>(io::root << homu); static_assert(v2 == "homu:14", ""); std::cout << v2 << std::endl; return 0; }
[出力]
test42 homu:14
以前、わたしも constexpr stringstream を書いてみたんですが、それとは使い勝手がだいぶ違いますね。
使う側としては stringstream の方が使い慣れている感じがするのですが、さて。
あと scientific みたいな書式は、値ではなくてそのストリームの式のみ有効になればいいんじゃないかなーと思わなくもない。
io::root << hex << 255 << '.' << 255 << '.' << 255 << '.' << 255; // やや助長 io::root << (255|hex) << '.' << (255|hex) << '.' << (255|hex) << '.' << (255|hex);
まぁ遅延処理するのが手間そうですが、
あと下記のコードだとコンパイルエラーとランタイムエラーになりました。
// コンパイルエラー constexpr auto os = io::root << 42; constexpr auto str = io::output<16>(os << "homu"); std::cout << str << std::endl; // ランタイムエラー std::cout << io::output<16>(io::root << "homuhomu") << std::endl;
ランタイムエラーになるのが気持ち悪い…。