Friday, 12 June 2009

Lists of data.

I've got to list out a load of stock items, make an enum entry for each of the items, and then add information about each stock type to a set of global arrays. The chance of me forgetting one of the arrays, or getting a position in one of the arrays wrong, is so high that I have to use a system to ensure simpler updates and more secure ordering of the data.

Along comes a technique I learnt a long time ago, someone called it the XMACRO system, well, I still call mine XMACRO, but it's just habit.

have a look at these three files to see how it works.

---- Stock.hxx ----

//XMACRO( xEnum, xName, xStockLow, xStockHigh, xStockPriceLow, xStockPriceNormal, xStockPriceHigh )
XMACRO( ST_FUEL, "Fuel", 20, 200, 3, 5, 8 )
XMACRO( ST_FOOD, "Food", 40, 200, 3, 5, 10 )
XMACRO( ST_WATER, "Water", 40, 200, 3, 5, 10 )
XMACRO( ST_STUFF, "Stuff", 50, 200, 10, 20, 60 )

---- StockTypes.h ----

#ifndef _STOCK_TYPES_H_
#define _STOCK_TYPES_H_

#define XMACRO( xEnum, xName, xStockLow, xStockHigh, xStockPriceLow, xStockPriceNormal, xStockPriceHigh ) xEnum,
enum STOCK_TYPE
{
#include "Stock.hxx"
NUM_STOCK_TYPES
};
#undef XMACRO

extern int gStockLow[ NUM_STOCK_TYPES ];
extern int gStockHigh[ NUM_STOCK_TYPES ];
extern int gStockNormalPrice[ NUM_STOCK_TYPES ];
extern int gStockLowPrice[ NUM_STOCK_TYPES ];
extern int gStockHighPrice[ NUM_STOCK_TYPES ];

#endif _STOCK_TYPES_H_

---- StockTypes.cpp ----

#include "StockTypes.h"

#define XMACRO( xEnum, xName, xStockLow, xStockHigh, xStockPriceLow, xStockPriceNormal, xStockPriceHigh ) xStockLow,
int gStockLow[ NUM_STOCK_TYPES ] =
{
#include "Stock.hxx"
};
#undef XMACRO

#define XMACRO( xEnum, xName, xStockLow, xStockHigh, xStockPriceLow, xStockPriceNormal, xStockPriceHigh ) xStockHigh,
int gStockHigh[ NUM_STOCK_TYPES ] =
{
#include "Stock.hxx"
};
#undef XMACRO

.......



What we have is a macro being defined, then being used to generate lines of information by including a file that is made solely out of those macro calls.
This technique lets you add and remove items very easily, as all you have to do is modify one file to add or remove or adjust a line of data.
Post a Comment