Conditional compilation on availability?

Fredrik Olsson peylow at gmail.com
Sun Jul 9 06:26:01 PDT 2006


Bruno Medeiros skrev:
> Kirk McDonald wrote:
> 
>> Fredrik Olsson wrote:
>>
>>> Might be an easy one, or a missing feature :).
>>>
>>> But how do I do a conditional compilation on the availability of a 
>>> function, variable, type or whatever?
>>>
>>> For example:
>>>
>>> class foo(T) {
>>>  T[] bar;
>>>   static if ("predicate for toString(T) exists") {
>>>     char[] allBarsConcatinatedAsString() {
>>>       char[] r = ""
>>>       foreach (v; bar) {
>>>     r ~= toString(v);
>>>       }
>>>     }
>>>   }
>>> }
>>>
>>> What would I type instead of "predicate for toString(T) exists"?
>>>
>>> // Fredrik
>>
>>
>> class foo(T) {
>>     static if (is(typeof(toString(T.init)))) {
>>         // ...
>>     }
>> }
>>
>> The IsExpression tests whether a given type is valid. typeof gets the 
>> type of a given expression. Thus, you can use one inside the other to 
>> test whether a given expression exists. Additionally, the expression 
>> inside of typeof is not actually executed, so it's safe to "call" the 
>> function like this.
>>
> 
> Note that that doesn't work if T is a static array, since
> typeof(T) != typeof(T.init) but instead typeof(T.init) == typeof(*T) 
> (which is viewed by some of us as a nasty inconsistency).
> Best to do as in Tom's example.
> 
> 

Thanks Kirk, Tom and Bruno. I got it too work.

But for a more general case perhaps:
static if(expression) should yield false if expression is false, _or_ if 
the expression can not be resolved. So that for example these could work:
static if (toString(int)) { /* jupp std.strings probably imported */ }
static if (T.nan) { /* Would seem we have a float */ }
etc.

But that is just wishes.

// Fredrik



More information about the Digitalmars-d-learn mailing list