www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to get value of type at CT given only an alias

reply FoxyBrown <Foxy Brown.IPT> writes:
Trying to do some tricky stuff but I can't seem to get the value 
of a type(enum in my case, but must work in general).

Basically, given a type T or an alias T(alias preferred), I'd 
like to be able to get the "default value" of that type.

e.g.,

if it is an enum and I have an alias to a member, instead of 
(Enum)3 I want 3.

if it is a member field, I want the default value.

if it is a function pointer, the address(probably 0, but 
whatever).

Basically a sort of generic "getValue" that attempts to get the 
CT value of any type, if it exists. (obviously the value of class 
is meaningless, so returns ""... class isn't even a type, but can 
still query).

In fact, I'd like to also naturally resolve the value back in to 
the expression that created it.

e.g.,

(Enum)3 -> Enum.ThirdEntry
Jul 14
parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 7/14/17 1:51 PM, FoxyBrown wrote:
 Trying to do some tricky stuff but I can't seem to get the value of a 
 type(enum in my case, but must work in general).
 
 Basically, given a type T or an alias T(alias preferred), I'd like to be 
 able to get the "default value" of that type.
 
 e.g.,
 
 if it is an enum and I have an alias to a member, instead of (Enum)3 I 
 want 3.
 
 if it is a member field, I want the default value.
 
 if it is a function pointer, the address(probably 0, but whatever).
 
 Basically a sort of generic "getValue" that attempts to get the CT value 
 of any type, if it exists. (obviously the value of class is meaningless, 
 so returns ""... class isn't even a type, but can still query).
 
 In fact, I'd like to also naturally resolve the value back in to the 
 expression that created it.
 
 e.g.,
 
 (Enum)3 -> Enum.ThirdEntry
 
 
.init is the default value. I'm not sure you can get the default value of a non-default initializer, My attempts using init didn't work. e.g.: void foo(alias T)() { pragma(msg, T.init); } struct S { int y = 5; void bar() { foo!y; } // prints 0 } -Steve
Jul 14
parent Moritz Maxeiner <moritz ucworks.org> writes:
On Friday, 14 July 2017 at 18:06:49 UTC, Steven Schveighoffer 
wrote:
 .init is the default value.

 I'm not sure you can get the default value of a non-default 
 initializer, My attempts using init didn't work. e.g.:

 void foo(alias T)()
 {
    pragma(msg, T.init);
 }

 struct S
 {
    int y = 5;
    void bar() { foo!y; } // prints 0
 }
See spec [1]: "If applied to a variable or field, it is the default initializer for that variable or field's type." If you want to get at the 5 in a static context, you'd have to use --- S.init.y --- i.e. get the default initializer for the struct and get its y member's value. [1] https://dlang.org/spec/property.html#init
Jul 14