Conditional compilation on availability?
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Sun Jul 9 03:25:44 PDT 2006
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.
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d-learn
mailing list