Coming from my background in dynamic languages, I find I have a problem expressing my intentions in a statically-typed language such as C++.
I’m designing a preference system for my application. As every preference will have a few associated values (the default value, limits, an observer function…) I decided to encapsulate each preference in an object of its own. Here’s my first draft:
class Preference // purely abstract class
{
parseFromString(String s) = 0;
get() = 0;
void set(newVal) = 0;
private:
// internal data
};
Now I need to create a few derived classes, like IntPreference, FloatPreference and StringPreference. Here’s how their declaration would look like:
class IntPreference : Preference class StringPreference : Preference
{ {
int parseFromString(String s); String parseFromString(String s);
void set(int newVal); void set(String newVal);
// etc. // etc.
} }
Now that the set() method takes an int parameter in the class IntPreference and a String parameter in StringPreference, there’s no way to declare this function in the base class. The same goes with the return value of parseFromString(). I understand this is impossible to do in C++, because functions with the same name and different parameter types in a derived class just overshadow, not override their ancestors. Again, this is how I would express myself in a dynamic language, what’s the correct pattern in C++?
EDIT: Sorry, I forgot to mention I need a base class to store them all in a hash table:
Hash(const char *name, Preference pref);
What you have now, is a poor
boost::anyclass and you maybe shouldsimply just use that.
Your
parseFromString()member function is dubious. You use thedynamic type to decide what to parse out of the string, something that
always has to be known statically.
If you dislike templates you can simply provide a few defaults:
EDIT: If
boost::anyis too generic for you and you want to limityour construct to a certain set of values use
boost::variant. Although a variant has a larger impact on compiletime and can be quite hard to use for a beginner.
EDIT2: The hash table problem: