April 20, 2011

For what it's worth, I have finally found one use case for the famous "alias this" trick for structs:

struct ScienceConstant {
    float value;
    string name;
    alias value this;
    string toString () { return this.name; }

unittest {
    auto PI = ScienceConstant(3.14, "pi");
    writefln("%s/3 = %s", PI, PI/3);
    // --> pi/3 = 1.04667

For people who don't know it: the point is that "alias this" implicitely delegates messages (here requests for arithmetic operations) to the actual element (here value) on which they should apply, that happens to be embedded in a struct object. Or rather: that's how I conceive this feature.

vita es estrany

Top | Discussion index | About this forum | D home