Conditional compilation on availability?
Kirk McDonald
kirklin.mcdonald at gmail.com
Sat Jul 8 15:52:03 PDT 2006
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.
--
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki
More information about the Digitalmars-d-learn
mailing list