www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - static check for float type or existence of a function overload

reply Bill Baxter <wbaxter gmail.com> writes:
I'd like to do something like this:
     static if (is(Type.epsilon)) {
         // Type is fp type
         alias Type RType;
         static final bool isfloat = true;
     } else {
         // type is not fp type
         alias real RType;
         static final bool isfloat = false;
     }

I thought the is(Type.epsilon) would fail only if Type didn't have an 
epsilon, but it seems to fail no matter what.

Is there another way to achieve this other than enumeration of the float 
types, i.e.
  static if (is(Type==float) || is(Type==double) || is(Type==real))...

I'd rather use duck typing here, i.e. if it has some property that makes 
it float-like, then do one thing, otherwise do another.

Actually what I *really* want to do is just special case types for which 
a particular funtion is not defined.  E.g. sqrt().  If sqrt() doesn't 
exist for the type then I'd like to do something else (because it won't 
compile with the call to sqrt in there...)

Is there a way to achieve that other than the enumeration of the things 
I know have a sqrt?  Problem with that is a user can easily provide a 
sqrt for their type.  So I have no way of knowing in advance what types 
have sqrt functions and which don't.

--bb
Oct 24 2006
parent reply Thomas Kuehne <thomas-dloop kuehne.cn> writes:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Bill Baxter schrieb am 2006-10-24:
 I'd like to do something like this:
      static if (is(Type.epsilon)) {
          // Type is fp type
          alias Type RType;
          static final bool isfloat = true;
      } else {
          // type is not fp type
          alias real RType;
          static final bool isfloat = false;
      }

 I thought the is(Type.epsilon) would fail only if Type didn't have an 
 epsilon, but it seems to fail no matter what.

is(typeof(Type.epsilon))
 Actually what I *really* want to do is just special case types for which 
 a particular funtion is not defined.  E.g. sqrt().  If sqrt() doesn't 
 exist for the type then I'd like to do something else (because it won't 
 compile with the call to sqrt in there...)

 Is there a way to achieve that other than the enumeration of the things 
 I know have a sqrt?  Problem with that is a user can easily provide a 
 sqrt for their type.  So I have no way of knowing in advance what types 
 have sqrt functions and which don't.

sure: static if(is(typeof(sqrt(Type.init)))){ ... } Thomas -----BEGIN PGP SIGNATURE----- iD8DBQFFPqD5LK5blCcjpWoRAg/zAJ0XO07miGQbmUdy3bAFx4F4Uvi7NwCeIR3S a+FCYilH4V0gpsso/sXN6rc= =Zj6R -----END PGP SIGNATURE-----
Oct 24 2006
parent Bill Baxter <wbaxter gmail.com> writes:
Thomas Kuehne wrote:
 
 is(typeof(Type.epsilon))

 static if(is(typeof(sqrt(Type.init)))){
 	...
 }

Excellent! Thanks. --bb
Oct 25 2006