Annotation of functions

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Feb 20 13:44:53 UTC 2018


On Tuesday, February 20, 2018 13:04:42 psychoticRabbit via Digitalmars-d 
wrote:
> On Tuesday, 20 February 2018 at 12:55:31 UTC, psychoticRabbit
>
> wrote:
> > fn string creater() pure {
> >
> >     return "void func() {}";
> >
> > }
> >
> > so now I'm just looking for lines that begin with fn. the mixin
> > doesn't matter.
>
> oh... I think I might have misunderstood your point ... due to
> not understanding CTFE. Never used it before - 25+ years
> programming ;-)
>
> what does this code even do? i don't understand it. why does it
> even compile?
>
>
> string creator() pure {
>   return "void func() {}";
> }
>
> mixin(creator());

mixin takes a string and that string is basically copy-pasted in as code.
So, in that example, you end up with

mixin(creator());

being replaced with

void func() {}

The example shows a really basic example of a string mixin - so basic as to
be pointless - but it gives you the basic idea. In general, when string
mixins are used, they're actually a lot more complicated, but they can be a
very useful tool for code generation.

One place where they get used frequently where they actually tend to be
simple is for operator overloading. e.g. this is
std.datetime.date.DateTime's opBinary:

DateTime opBinary(string op)(Duration duration)
    if (op == "+" || op == "-")
{
    DateTime retval = this;
    immutable seconds = duration.total!"seconds";
    mixin("return retval._addSeconds(" ~ op ~ "seconds);");
}

D's overloaded operators were specifically designed to be used with string
mixins in order to allow you to use the same function for overloading
multiple operators.

- Jonathan M Davis



More information about the Digitalmars-d mailing list