Friday, June 4, 2021

 After I gave up on the madness that is C++, I looked for an alternative. I wanted garbage collection, strong typing and object orientation. I quickly found D. Coming from a C background, it took be a while to adjust, but so far D has not disappointed me. I've used it for a GTK UI and a web backend. It compiles fast and runs fast.

Today I found a feature that I would never have guessed existed, but it solved the exact problem I had. Here's an example:

import std.stdio;
import std.string;

struct Life
{
    alias question this;
    string question = "What is the meaning";
    int answer = 42;

    void showAnswer ()
    {
        writeln ("The answer is ", answer);
    }
}


void main()
{
    Life l;

    string a = l ~ " of life?";
    writeln (a);

    Life foo = l;
    foo.showAnswer ();
}

I wanted a custom type so I could define my own member functions, but I also have to use a library that uses string concatenation on it's parameters. By aliasing "this" to the member "question", variables of type Life can also behave as if they are of type string.

This feels almost like magic, but it's just an example of how flexible D is and how clever it's compiler is.