What is the syntax to test for specific types in templates

Derek Parnell derek at psych.ward
Tue Apr 11 21:44:48 PDT 2006


I want to ensure that the template can only be generated for certain data
types: integers and floating-point numbers only. I've seen something like
this done before but I cannot work it out fro the official documentation.

I think it should be something like ...

template foo(T)
{
   T foo(T x)
   {
      static if ( is(ulong T) ||
                  is(long T)  ||
                  is(uint T)  ||
                  is(int T)  ||
                  is(ushort T)  ||
                  is(short T)  ||
                  is(ubyte T)  ||
                  is(byte T) )
      {
         // ... code for integers ... //
      }
      else
      static if ( is(real T) ||
                  is(double T)  ||
                  is(float T) )
      {
         // ... code for floating points ... //
      }
      else
      {
         pragma(msg, "Only integers and floating points");
         static assert(0);
      }

   }
}

I know I can use template specialization but that is *way* too cumbersome
as I'd need three copies of the floating point template and eight copies of
the integer template. And seeing that templates were invented to avoid all
this copying it seems odd that there is not easy way to do multiple
specialization. 

Even if we could do ...

  template foo(T : (ulong, long, uint, int, ushort, short, ubyte, byte) )
  {
    // code for integers 
  }

  template foo(T : (real, double, float) )
  {
    // code for floating points
  }

would be useful but I don't think anything like this is allowed.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
12/04/2006 2:07:10 PM



More information about the Digitalmars-d mailing list