Template constructor in a non-template struct.
ChrisG via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Feb 8 14:19:34 PST 2015
Thanks bearophile. Your first suggestion about making the struct
a template is something I considered. However, because of all the
code I've already written that approach would force me to use
inheritance or convert a ton of functions to templates. Ick.
The __ctor syntax looks like the answer to my question. If my
struct is used by anyone else though, I'm not sure it would be OK
to assume they would even be aware of that syntax. hmmm...
Thinking I'll just make it a runtime parameter for now.
Thank you.
-Chris
On Sunday, 8 February 2015 at 21:58:40 UTC, bearophile wrote:
> 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