Thursday, March 17, 2011

Engine Coding Tricks

Okay so when it comes to making a game engine sometimes you just need a uniform type that can be assigned any data, usually for a game console or command system of some sort, the only issue is you don't always know the type you're working with.  In some cases I've seen people handle everything as a string, while this may be effective it's in no case efficient.  In other cases I've seen interesting uniform classes that require some serious skill to debug and step through.  Some of the implementations are insane in code length and require outside sources from the all evil boost.

Anyways with some experimenting I've developed a farily straight forward class that allows me to assign any type of data and retrieve that data using the typename as the template paramater.

struct anytype {
   union anycore {
     int        i;
     float     f;
     double d;
     char *  s;
   template<typename T>
   void operator =(T t) { dat = *((T*)&t); }
   template<typename T>
   T get() { return *((T*)&dat); }
   anycore dat;

with this simple structure you can easily assign and get data here is an example:

anytype a[3];
a[0] = "this is a test";
a[1] = 65;
a[2] = 78.76f;

getting the data is just as easy:
char* data0 = a[0].get<char*>();
int     data1 = a[1].get<int>    ();
float  data2 = a[2].get<float> ();

I left out some sanity checks but you get the idea.

No comments:

Post a Comment