Preliminary submission - std.rational and std.typelist
Artur Skawina
art.08.09 at gmail.com
Sun Oct 7 10:05:20 PDT 2012
On 10/07/12 17:24, Philippe Sigaud wrote:
> On Sun, Oct 7, 2012 at 11:15 AM, Dmitry Olshansky <dmitry.olsh at gmail.com> wrote:
>> import std.stdio, std.format;
>>
>> struct A{
>> int k;
>>
>> void toString(scope void delegate(const(char)[]) sink)
>> {
>> formattedWrite(sink, "[%d]", k);
>> }
>> }
>
> I see, thanks. And if the string in formattedWrite is a complex beast,
> created through lots of if's and while's, I use Appender in its place?
You can write to the sink directly, eg
struct EnumBits(alias E) {
E e;
alias e this;
void toString(DG, FT)(scope DG sink, in FT fmt) const {
import std.format;
sink(E.stringof ~ "{");
int wrote;
foreach (member; __traits(allMembers, E))
if (__traits(getMember, E, member) & e){
if (wrote++) sink("|");
sink(member);
}
if (!wrote)
sink("/*No " ~ E.stringof ~ "*/");
sink("}");
}
}
It gets a bit more tricky when you for example need to print the
contents of containers w/o copying the data; but you can then just
call their toString method directly:
struct PTR_LIST(T, bool TAGGED=0) {
c_int nr;
PTR_LIST *prev;
PTR_LIST *next;
// ...
void toString(DG, FT)(scope DG sink, in FT fmt) const {
import std.format;
sink(typeof(cast()this).stringof ~ "{[");
formatValue(sink, nr, fmt); sink("]");
foreach (p; this) {
p.toString(sink, fmt);
sink(", ");
}
sink("}");
}
static struct Anchor {
PTR_LIST* list;
// ...
void toString(DG, FT)(scope DG sink, in FT fmt) const {
import std.format;
// Cannot 'formatValue(sink, *list, fmt);' as the struct is passed
// by value and that messes up the list (head pointer doesn't match).
list.toString(sink, fmt);
}
}
}
/* Obviously, i wasn't trying to avoid allocations, hence the presence of '~'s. */
artur
More information about the Digitalmars-d
mailing list