Re: Is a type-safe callback mechanism possible?
Adam Nielsen <adam.nielsen@remove.this.uq.edu.au> wrote:
I'm trying to use type-safe code with templates, but I'm a bit stuck as
to how you can call into a type-specific template when all you have is a
pointer to its base class.
The code below demonstrates the problem, along with the only solution I
have come up with...
(quotes below taken from "Design Patterns", by Gamma et al.)
What you have implemented is the Visitor design pattern, with the
CDatabase representing the Visitor, IDatabaseField representing the
Element and your various sub-classes of IDatabaseFIeld representing the
ConcreteElements.
One of the consequences listed of the Visitor pattern is that it "...
makes adding new operations easy." while "adding new ConcreteElement
classes is hard."
You haven't fully implemented the Visitor pattern though, because you
made your CDatabase class concrete rather than abstract, so as a
consequence even adding new operations is harder than it should be. :-(
But before fleshing out the pattern, let's revisit the issue and see if
the pattern is even appropriate here...
class CDatabase
{
public:
// This function adds some data to a database in a
// type-specific way.
template <typename T>
void add(const T& tData) {
// Add tData into the database, depending on what type it is.
std::cout << "Adding some data of type " << typeid(T).name()
<< std::endl;
}
};
Does the above "add" function work for all needed types or do you have
further specializations? If it does work for all the types you need, is
it a template function simply because there is no generic class
representing ints and floats and such? Maybe there is a way to expose a
more primitive interface?