Template constructor in a non-template struct.

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Feb 8 13:58:38 PST 2015


ChrisG:

> I don't really understand how I'd differentiate a constructor 
> template from a class/struct template.

One solution is to use a template struct (struct/class names 
start with an upper case in D, while typed enum members usually 
start with a lower case):


enum E { option1, option2 }

struct Boring(E Opt = E.option1) {
     this(int arg1, int arg2) {}
}

void main() {
     auto a = Boring!(E.option2)(1, 2);
}


If you want to instantiate the constructor template without type 
inference, then this seems to work, but it's not idiomatic D:


enum E { option1, option2 }

struct Boring {
     this(E Opt = E.option1)(int arg1, int arg2) {}
}

void main() {
     auto a = Boring().__ctor!(E.option2)(1, 2);
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list