libostd/examples/format.cc

87 lines
2.0 KiB
C++
Raw Normal View History

2016-02-03 22:21:53 +01:00
#include <ostd/algorithm.hh>
#include <ostd/vector.hh>
#include <ostd/map.hh>
#include <ostd/range.hh>
#include <ostd/io.hh>
#include <ostd/tuple.hh>
using namespace ostd;
struct Foo {
};
/* implementing formatting for custom objects - external function */
template<typename R>
2016-06-23 20:18:35 +02:00
bool to_format(Foo const &, R &writer, FormatSpec const &fs) {
2016-02-03 22:21:53 +01:00
switch (fs.spec()) {
case 'i':
writer.put_string("Foo1");
break;
default:
writer.put_string("Foo2");
break;
}
return true;
}
struct Bar {
/* implementing formatting for custom objects - method */
template<typename R>
2016-06-23 20:18:35 +02:00
bool to_format(R &writer, FormatSpec const &fs) const {
2016-02-03 22:21:53 +01:00
switch (fs.spec()) {
case 'i':
writer.put_string("Bar1");
break;
default:
writer.put_string("Bar2");
break;
}
return true;
}
};
int main() {
Vector<int> x = { 5, 10, 15, 20 };
writefln("[%(%s|%)]", x);
int y[] = { 2, 4, 8, 16, 32 };
writefln("{ %(%s, %) }", y);
writefln("[\n%([ %(%s, %) ]%|,\n%)\n]", map(range(10), [](int v) {
return range(v + 1);
}));
Map<String, int> m = {
{ "foo", 5 },
{ "bar", 10 },
{ "baz", 15 }
};
/* strings and chars are automatically escaped */
writefln("{ %#(%s: %d, %) }", m);
/* can override escaping with the - flag,
* # flag expands the element into multiple values
*/
writefln("{ %-#(%s: %d, %) }", m);
/* tuple format test */
2016-06-23 20:18:35 +02:00
Tuple<int, float, char const *> xt[] = {
2016-02-03 22:21:53 +01:00
make_tuple(5, 3.14f, "foo"),
make_tuple(3, 1.23f, "bar"),
make_tuple(9, 8.66f, "baz")
};
writefln("[ %#(<%d|%f|%s>%|, %) ]", xt);
/* custom format */
2016-05-25 18:12:28 +02:00
writefln("%s", Foo{});
writefln("%i", Foo{});
2016-02-03 22:21:53 +01:00
/* custom format via method */
2016-05-25 18:12:28 +02:00
writefln("%s", Bar{});
writefln("%i", Bar{});
2016-02-03 22:21:53 +01:00
/* format into string */
auto s = appender<String>();
format(s, "hello %s", "world");
writeln(s.get());
2016-02-07 22:17:15 +01:00
}