Emulating Dynamic Dispatch in C++ based on Template Parameters
- by Jon Purdy
This is heavily simplified for the sake of the question. Say I have a hierarchy:
struct Base {
virtual int precision() const = 0;
};
template<int Precision>
struct Derived : public Base {
typedef Traits<Precision>::Type Type;
Derived(Type data) : value(data) {}
virtual int precision() const { return Precision; }
Type value;
};
I want a function like:
Base* function(const Base& a, const Base& b);
Where the specific type of the result of the function is the same type as whichever of first and second has the greater Precision; something like the following pseudocode:
template<class T>
T* operation(const T& a, const T& b) {
return new T(a.value + b.value);
}
Base* function(const Base& a, const Base& b) {
if (a.precision() > b.precision())
return operation((A&)a, A(b.value));
else if (a.precision() < b.precision())
return operation(B(a.value), (B&)b);
else
return operation((A&)a, (A&)b);
}
Where A and B are the specific types of a and b, respectively. I want f to operate independently of how many instantiations of Derived there are. I'd like to avoid a massive table of typeid() comparisons, though RTTI is fine in answers. Any ideas?