Say if I want to extend the functionality of a range of objects that I cannot change - for instance for adding formatting, and don't want to derive a huge amount of classes to extend the functionality - would the following considered bad? (I'm using int and float as an example, but in my program I have about 20 or 30 classes that will end up in a tree that will contain a generic type).
class ITreeNode
{
public:
virtual ~ITreeNode() {}
virtual void print() = 0;
};
template <class T>
class ObjectNode : public virtual ITreeNode
{
public:
virtual ~ObjectNode() {}
ObjectNode(T v)
{
m_var = v;
}
void print()
{
print(m_var);
}
protected:
void print(int i)
{
printf("int (%d)\r\n", m_var);
}
void print(float f)
{
printf("float (%f)\r\n", m_var);
}
T m_var;
};
int _tmain(int argc, _TCHAR* argv[])
{
ObjectNode<int> tInt(5);
ObjectNode<float> tFloat(5.5);
tInt.print();
tFloat.print();
getchar();
return 0;
}
Basically I need a tree of objects (all of the same base type) that I can call with these extended functions. Originally I was using the visitor pattern and creating a visitor class for every one extended bit of functionality I needed. This seemed very cumbersome and thought maybe the above would be better.
I thought I'd post here first as a sanity check..
Thanks in advance.