www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Use enum base type?

reply "Janissary" <janissary janissary.janissary> writes:
Is it possible to evaluate an enum's base type? Ideally something 
like:

enum somestrs : string { ... }
enum d = 0.0;
template EnumBaseType(E) if (is(E==enum)) { ... }
unittest {
    static assert( is(EnumBaseType!somestrs == string) );
    static assert( is(EnumBaseType!d : float) );
    static assert(!is(EnumBaseType!d == float) );
}

A template like this would make at least my life easier.
Apr 17 2013
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On 2013-04-17, 19:15, Janissary wrote:

 Is it possible to evaluate an enum's base type? Ideally something like:

 enum somestrs : string { ... }
 enum d = 0.0;
 template EnumBaseType(E) if (is(E==enum)) { ... }
 unittest {
     static assert( is(EnumBaseType!somestrs == string) );
     static assert( is(EnumBaseType!d : float) );
     static assert(!is(EnumBaseType!d == float) );
 }

 A template like this would make at least my life easier.
Whenever you want to do weird stuff with types, std.traits[1] should be your #1 stop. And quite correctly, std.traits.OriginalType[2] does what you want: enum E : int { a } typedef E F; typedef const F G; static assert(is(OriginalType!G == const int)); [1]: http://dlang.org/phobos/std_traits [2]: http://dlang.org/phobos/std_traits#.OriginalType -- Simen
Apr 17 2013
parent "Janissary" <janissary janissary.janissary> writes:
On Wednesday, 17 April 2013 at 18:56:43 UTC, Simen Kjaeraas wrote:
 On 2013-04-17, 19:15, Janissary wrote:

 Is it possible to evaluate an enum's base type? Ideally 
 something like:

 enum somestrs : string { ... }
 enum d = 0.0;
 template EnumBaseType(E) if (is(E==enum)) { ... }
 unittest {
    static assert( is(EnumBaseType!somestrs == string) );
    static assert( is(EnumBaseType!d : float) );
    static assert(!is(EnumBaseType!d == float) );
 }

 A template like this would make at least my life easier.
Whenever you want to do weird stuff with types, std.traits[1] should be your #1 stop. And quite correctly, std.traits.OriginalType[2] does what you want: enum E : int { a } typedef E F; typedef const F G; static assert(is(OriginalType!G == const int)); [1]: http://dlang.org/phobos/std_traits [2]: http://dlang.org/phobos/std_traits#.OriginalType
Thanks, that's just what I needed.
Apr 17 2013