On Monday, 7 August 2017 at 08:01:26 UTC, Shachar Shemesh wrote:
The problem is what happens when the param is optional. The common way to do this is to set T to void. This results in the following code:

struct S(T) {
        enum HasParam = !is(T == void);
        static if( HasParam ) {
                T param;
        }

        static if( HasParam ) {
                void initialize(T param) {
                        this.param = param;
                        // Other stuff
                }
        } else {
                void initialize() {
                        // Same other stuff as above!
                }
        }
}

This is both tedious and error prone. Is there a cleaner way of doing this?

Shachar

I was going to suggest using Algebraic/Variant, as in:

    void initialize(Algebraic!(int,void)) {
        static if(hasParam)
            this.param = param;
        // Other stuff
    }

but unfortunately Algebraic seems very cumbersome to use. You can't call initialize with an int (or "parameterlessly"); you have to use it like this:

    x.initialize(Algebraic!(int,void)(my_integer)); //

which is bad in many ways, e.g. you'll have to import std.variant whenver you want to call initialize.

Ideally, I would have liked to write something like this:

    void initialize( static if(hasParam) { mixin("T param"); } ) {
        static if(hasParam) {
            this.param = param;
        }
        // Other stuff
    }

but of course this is currently not possible.

Reply via email to