static if check for array and AA
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed Jun 21 15:45:12 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
Now there's an idea... The templates are now:
template isArray(T) {
const bool isArray = is(typeof(T.init[0])[] == T);
}
template isAA(T) {
const bool isAA =
is(typeof(T.init.values[0])[typeof(T.init.keys[0])] == T);
}
I'd forgotten about those .keys and .values properties. :-)
-Kirk McDonald
More information about the Digitalmars-d
mailing list