www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.announce - A useful template and a bug

I have found the following template to be quite useful for file IO. Just 
thought I'd post it.

BTW  if it is compiled with the -D option the it gets the this error

data.d(14): Error: static if conditional cannot be at global scope

from doc:
"StaticIfConditions cannot appear at module scope. They can appear in 
class, template, struct, union, or function scope"

---------------------------
/**
  * A template providing raw access to a file stream.
  * Authors:  Benjamin Shropshire
  *           shro_8822 uidaho edu  (remove '_')
  * Date:     12/30/2005
  * Version:  1.0
  */
template Data(T)
{
     // Make sure objects aren't used
     // (they wouldn't work right)
   static assert(!is(T:Object));

     // Warn if used with a pointer
     //(they most likely aren't what is wanted)
   static if(is(T:void*))
   {
     pragma(msg,
     "Data!(T) used with a pointer type, is this intended?\n");
   }

     /// Read and ignore the right amount of data from the stream.
   void Discard(Stream ins)
   {
     T ret;
     ins.readExact(&ret, T.sizeof);
     return;
   }

     /// Read and return one of the given type from the stream.
   T Read(Stream ins)
   {
     T ret;
     ins.readExact(&ret, T.sizeof);
     return ret;
   }

     /// Read and return i of the given type from the stream.
   T[] Read(Stream ins, int i)
   {
     T[] ret = new T[i];
     ins.readExact(ret.ptr, T.sizeof*i);
     return ret;
   }

     /// Write enough data for one of the given type to the stream
   void Write(Stream ins)
   {
     T dat;
     ins.writeExact(&dat, T.sizeof);
   }

     /// Write all of dat's elements to the stream.
   void Write(Stream ins, T[] dat)
   {
     ins.writeExact(dat.ptr, T.sizeof*dat.length);
   }

     /// Write dat to the stream.
   void Write(Stream ins, T dat)
   {
     ins.writeExact(dat, T.sizeof);
   }
}
Dec 30 2005