static if check for array and AA

Kirk McDonald kirklin.mcdonald at gmail.com
Wed Jun 21 15:33:56 PDT 2006


I'm fairly certain I've seen this come up before, but I can't seem to 
rediscover the thread.

I'm trying to write a static if condition to check whether a certain 
type is an array, and another check for an associative array. The former 
proved to be moderately simple:

bool isArray(T) () {
     static if (is(typeof(T.init[0])[] == T)) {
         return true;
     } else {
         return false;
     }
}

Note that this only checks for dynamic arrays.

Associative arrays are harder. The above trick can't quite work as the 
type of the key can't be relied upon. It's easy enough to do the check 
using RTTI:

bool isAA(T) () {
     TypeInfo t = typeid(T);
     if (cast(TypeInfo_AssociativeArray) t) {
         return true;
     } else {
         return false;
     }
}

But of course that is a runtime check, and this should really be a 
compile-time check. (Also, the various subclasses of TypeInfo are 
undocumented, so I'm not sure if it's a good idea to rely on them.)

Anyone else have some template judo to share?

-Kirk McDonald



More information about the Digitalmars-d mailing list