Conditional compilation on availability?

Tom S h3r3tic at remove.mat.uni.torun.pl
Sat Jul 8 15:51:54 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

The following seems to do the trick:



import std.string;


class foo(T) {
  T[] bar;
   static if (is(typeof(.toString(bar[0])))) {
     char[] allBarsConcatinatedAsString() {
       char[] r = "";
       foreach (v; bar) {
		  r ~= .toString(v);
       }
	  return r;
     }
   }
}



void main() {
	auto a = new foo!(int);
	a.allBarsConcatinatedAsString();

	struct Blah {}
	auto b = new foo!(Blah);
	//b.allBarsConcatinatedAsString();
}



-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d-learn mailing list