Inherit from class based on bool value

Ali Çehreli acehreli at yahoo.com
Tue Nov 13 07:29:30 UTC 2018


On 11/12/2018 11:10 PM, Jamie wrote:
 > I would like my class to inherit from one of two classes based on a
 > boolean value known at compile time. Something like this:
 >
 > void main()
 > {
 >      Top!(OPTION.FALSE) top = new Top!(OPTION.FALSE);
 > }
 >
 > enum OPTION
 > {
 >      FALSE = 0.,
 >      TRUE = 1.
 > }
 >
 > class One
 > {}
 >
 > class Two
 > {}
 >
 > class Top(OPTION option) : option ? One : Two
 > {}
 >
 > Is this possible? I can't get it to work in the way I'm showing above.
 > Cheers

I got it working inside an eponymous template. D is pretty cool actually. :)

enum OPTION
{
     FALSE = 0.,
     TRUE = 1.
}

class One
{}

class Two
{}

template Top(OPTION option) {
     static if (option == OPTION.TRUE) {
         alias Base = One;

     } else {
         alias Base = Two;
     }

     class Top : Base
     {}
}

void main() {
     auto a = new Top!(OPTION.FALSE);
     auto b = new Top!(OPTION.TRUE);
}

Ali



More information about the Digitalmars-d-learn mailing list