Re: Possible to create a "compile-time error" version of enum?
pete@pcbartlett.com wrote:
If I add a new value to an enum, then it is likely that I have to visit
all switch statements that use the enum and either add a new case
statement (or check that the default is satisfactory). This is
potentially error-prone (some such statements may be missed in a large
code base).
[sniped]
Do any brighter minds than mine have any ideas for making the "ideal
version" work?
The ideal version would involve replacing the entire enum/switch
concept by polymorphism. So the following code:
struct data_t
{
enum { A, B, C } type;
std::string data;
};
void processData(data_t data)
{
switch (data.type)
{
case data_t::A: doSomethingA(data); break;
case data_t::B: doSomethingB(data); break;
case data_t::C: doSomethingC(data); break;
default: break;
}
}
Should be replaced by either:
struct data_t
{
virtual void doSomething() = 0;
};
struct dataA_t : public data_t
{
void doSomething() { ... }
};
struct dataB_t : public data_t
{
void doSomething() { ... }
};
void processData(data_t* data) { data->doSomething(); }
or:
struct dataA_t
{
void doSomething() { ... }
};
struct dataB_t
{
void doSomething() { ... }
};
template <class T>
void processData(T data) { data.doSomething(); }
The one you use depends on what best fits your
specific needs.
Chris Carton
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]