Suppose I have a data type enum TreeTypes { TallTree, ShortTree, MediumTree }.
And I have to initialize some data based on one particular tree type.
Currently I have written this code:
int initialize(enum TreeTypes tree_type) {
if (tree_type == TallTree) {
init_tall_tree();
}
else if (tree_type == ShortTree) {
init_short_tree();
}
else if (tree_type == MediumTree) {
init_medium_tree();
}
return OK;
}
But this is some kind of stupid code repetition. I am not using any of the powerful C++ capabilities like templates.
How could I write this code better?
Thanks, Boda Cydo.
Your code is OK for two or three values, but you are right, you need something more industrial strength when you have hundreds of them. Two possible solutions:
use a class hierarchy, not enums – you can then use virtual functions and have the compiler work out which actual function to call
create a map of enum -> function, which you initialise at startup – your function calls then become something like
map[enum]->func()Templates don’t work so well here, because you are trying to make a decision at run-time, whereas templates do their stuff at compile-time.