static if check for array and AA

Don Clugston dac at nospam.com.au
Fri Jun 23 04:03:00 PDT 2006


BCS wrote:
> Kirk McDonald wrote:
>> 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
> 
> 
> template isAA(T)
> {
>     const isAA = is((cast(T)null).keys);
> }
> 
> ???
> 
> or something like that


template isAA(T)
{
	const bool isAA = T.mangleof[0]=='H';
}

template isStaticArray(T)
{
	const bool isStaticArray = T.mangleof[0]=='G';
}

template isDynamicArray(T)
{
	const bool isDynamicArray = T.mangleof[0]=='A';
}

You can check for ANYTHING in this way.
Of course this relies on the name mangling algorithm which is not yet 
stabilised and documented -- but which should be, by DMD 1.0.



More information about the Digitalmars-d mailing list