On Monday, 7 August 2017 at 08:01:26 UTC, Shachar Shemesh wrote:
It is often desired to have a struct with an extra parameter. The common way to do this is like so:

struct S(T) {
        T param;

        void initialize(T param) {
                this.param = param;
                // Other stuff
        }
}

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?

Just as an unrealistic fantasy, if the following code was legal, the problem would be resolved on its own:
void func(void p) {
        void param;

        param = p;

        return param;
}


Of course, that code has its own set of problems, and I'm not really suggesting that change.

Shachar

Why don't you use a factory method?

struct S(T)
{
    T p;

    static make(T p)
    {
        S s;
        s.p = p;

        return s;
    }

    static make()
    {
        return S();
    }
}

void main()
{
    auto s1 = S!int.make;
    auto s2 = S!string.make;
}

Reply via email to