class for "updatable enum"

P

Patrick Guio

Dear all,

I wonder whether anyone might have a better idea/solution to the
following. I need an associative container <int,string> for a limited
and defined number of values (enum-like) but ir must be able to be updated
with more pairs later. Here is the solution I have developed so long
All my enum-like int values are declared static const inside a namespace
as well as a struct with a static map<int,string> to keep the pairs.
The constructor is used to add new pairs later.

So here are the declarations enum.h

namespace myEnum
{
const static int boolean;
const static int character;
struct table
{
typedef map<int, const string> mymap;
typedef mymap::value_type mypair;
typedef mymap* iter;
table(const Iter & first, const Iter & last);
static ValuesDescList values;
};
}

And the definitions enum.cpp

#include <enum.h>

namespace myEnum {
const int boolean = 1;
const int character = 2;
namespace
{
table::mypair v_tableInit[] =
{
table::mypair(boolean , "bool"),
table::mypair(character, "char")
};
table::mypair *v_tableInitEnd(v_tableInit+
sizeof v_tableInit / sizeof v_tableInit[0]);
}
table::table(const Iter & first, const Iter & last)
{
values.insert(first, last);
}
// initialise static
table::mymap table::values(v_tableInit, v_tableInitEnd);
}

Now if I need to update the namespace with more pairs, here is what I
can do

#include <enum.h>

namespace myEnum
{
const static int boolVect = 100;
const static int realVect = 104;
namespace // seems to need namespace to avoid redef of v_tableInit and v_tableInitEnd
{
table::mypair v_tableInit[] =
table::mypair(boolVect, "bool[]"),
table::mypair(realVect, "real[]")
};
table::mypair *v_tableInitEnd(v_tableInit+
sizeof v_tableInit / sizeof v_tableInit[0]);
table registerMe(v_mapInit, v_mapInitEnd);
}

The trick is to use the constructor of table to insert new pairs in the
static table::values.
Then I can check

using namespace myEnym;
int main()
{
table::mymap::const_iterator i=table::value.begin()
do {
std::cout << i->first << " " << i->second << std::endl;
} while (i != valueMap::values.end());
}

Is this a reasonable solution? Anything that could improve it?

Sincerely,
Patrick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top