Abstract type
Abstract type

Reputation: 1921

How can I get the value type of an enum member

For example

template EnumValueType(T)
if (is(T == enum))
{
    alias EnumValueType = /* ??? */;
}

enum E: ubyte {e0 = 123}
enum D: float {d0 = 0.5}

void main()
{
    E e;
    D d;
    assert( is(EnumValueType!(typeof(e)) == ubyte));
    assert( is(EnumValueType!(typeof(d)) == float));
}

So far I can only detect if it's a enum. I see a way to do this but it's bad. It would consist in iterating trough an AliasSeq seq made of D basic types and to see if a T is convertible to seq[n].

Any other idea ?

Upvotes: 0

Views: 75

Answers (2)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26549

You might also want std.traits.OriginalType.

is returns the first enum base type, which may be another enum. OriginalType continues expansion until it gets the actual base type.

enum E : real { a }
enum F : E    { a = E.a }

static if(is(F Base == enum))
    pragma(msg, Base); // Prints "E"
else
    static assert(false);

import std.traits;
pragma(msg, OriginalType!F); // Prints "real"

Upvotes: 1

Mihails Strasuns
Mihails Strasuns

Reputation: 3803

You can use one of many versions of is expression:

enum E : float
{
    E1 = 2.0
}

static if (is(typeof(E.E1) Base == enum))
{
    pragma(msg, Base); // float
}

Implementation of your desired template could look like this:

template EnumValueType(T)
    if (is(T == enum))
{
    static if (is(T Base == enum))
        alias EnumValueType = Base;
}

Upvotes: 2

Related Questions