2008-12-11

Tip: Define data only once.

Have you ever done some programming where you realize that you have to enter the same data on several places? For instance, because you need some data for defining, e.g, an enumeration and the very same data when defining some other structure? It's a relatively common scenario. Study the following C++ example to see how to get rid of this duplicate work and only define one data set in one place. Let's define the data once, in a macro definition file we call macro.def:
#ifndef X
#error X not defined
#else
   X(a,1)
   X(b,2)
   X(c,3)
   X(d,4)
   X(e,5)
#endif
The data in this example are the a,...,e and 1,...5, you could easily extend this to more dimensions. Now, let's use this data in more than declaration/definition. Note how we include the macro file more than once and how we define and undefine the X macro as needed:
#define X(A,B) A,
enum object
{
#include "macro.def"
};
#undef X
 
#include <iostream>
#include <string>
 
class menu
{
   public:
      menu(const object& o,const std::string& name,const int& val):
         o(o),name(name),val(val) {};
      friend std::ostream& operator<<(std::ostream&,const menu&);
   private:
      object o;
      std::string name;
      int val;
};
std::ostream& operator<<(std::ostream& o,const menu& m)
{
   o << m.name << ": " << m.val;
   return o;
};
 
#include <map>
int main()
{
   std::map<object,menu> object_menu;
 
#define X(A,B) object_menu.insert(std::make_pair(A,menu(A,#A,B)));
#include "macro.def"
#undef X
 
   for( std::map<object,menu>::const_iterator
         i = object_menu.begin(),
         e = object_menu.end();
         i != e;
         ++i )
   {
      std::cout << i->second << '\n';
   }
   return 0;
}
On my machine, I get the following on standard output:
a: 1
b: 2
c: 3
d: 4
e: 5

0 kommentarer:

Post a Comment