Getting a Type from TypeInfo / Getting Variant Type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 11 09:57:15 UTC 2018


On Thursday, January 11, 2018 08:59:01 Chirs Forest via Digitalmars-d-learn 
wrote:
> I'm using std.variant.Variant to hold a value of unknown type
> (not a string, could be a numeric type or a container holding
> multiple numeric types). I'm trying to retrieve this value with
> .get!T but I need the type to do that... .type gives me TypeInfo,
> but that's not a type so I'm not sure how to get the type without
> checking the TypeInfo against all possible types (which would be
> a massive pain).

If you have a variable of the type you put in, then you can use the typeof
operator on it to get the type. e.g.

int i = 42;
static assert(is(typeof(i) == int));

It's even possible to declare variables of voldemort types that way - e.g.
if you want to save the result in a member variable.

But from what I can tell, you're either going to need to know the type you'r
dealing with, or you're going to need a variable of the type so that you can
then use typeof on it to get its type.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list