diff --git a/examples/format.cc b/examples/format.cc new file mode 100644 index 0000000..116d37a --- /dev/null +++ b/examples/format.cc @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include + +using namespace ostd; + +struct Foo { +}; + +/* implementing formatting for custom objects - external function */ +template +bool to_format(const Foo &, R &writer, const FormatSpec &fs) { + 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 + bool to_format(R &writer, const FormatSpec &fs) const { + switch (fs.spec()) { + case 'i': + writer.put_string("Bar1"); + break; + default: + writer.put_string("Bar2"); + break; + } + return true; + } +}; + +int main() { + Vector 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 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 */ + Tuple xt[] = { + 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 */ + writefln("%s", Foo()); + writefln("%i", Foo()); + + /* custom format via method */ + writefln("%s", Bar()); + writefln("%i", Bar()); + + /* format into string */ + auto s = appender(); + format(s, "hello %s", "world"); + writeln(s.get()); +} \ No newline at end of file