Okay, this is a bit complicated so please bear with me. :)
We have this simple class hierarchy:
class A {};
class DA : public A {};
class DDA : public DA {};
And we have the following functions operating on these classes:
void f(A x) {
std::cout << "f A" << std::endl;
}
void f(DA x) {
std::cout << "f DA" << std::endl;
}
void f(DDA x) {
std::cout << "f DDA" << std::endl;
}
Now we want to add another function that treats DA a little differently.
(1) A first attempt could look like this:
void g(A t) {
std::cout << "generic treatment of A" << std::endl;
std::cout << "called from g: ";
f(t);
}
void g(DA t) {
std::cout << "special treatment of DA" << std::endl;
std::cout << "called from g: ";
f(t);
}
But calling this with an object of each of the classes clearly does not have the desired effect.
Call:
A a; DA b; DDA c;
g(a); g(b); g(c)
Result:
generic treatment of A
called from g: f A
special treatment of DA
called from g: f DA
special treatment of DA
called from g: f DA //PROBLEM: g forgot that this DA was actually a DDA
(2) So instead we might try to use templates:
template<typename T>
void h(T t) {
std::cout << "generic treatment of A" << std::endl;
std::cout << "called from h: ";
f(t);
}
template<>
void h<>(DA t) {
std::cout << "special treatment of DA" << std::endl;
std::cout << "called from h: ";
f(t);
}
which results in:
generic treatment of A
called from h: f A
special treatment of DA
called from h: f DA
generic treatment of A //PROBLEM: template specialization is not used
called from h: f DDA
Well, how about we don't use template specialization but define a non-template function for the special case? (Article on the very confusing matter.) It turns out it behaves in exactly the same way because the non-template function which is according to the article a "first class citizen", seems to lose because a type conversion is necessary to use it. And if it would be used, well then we would just be back at the first solution (I assume) and it would forget the type of DDA.
(3) Now I came across this code at work which seems rather fancy to me:
template<typename T>
void i(T t, void* magic) {
std::cout << "generic treatment of A" << std::endl;
std::cout << "called from i: ";
f(t);
}
template<typename T>
void i(T t, DA* magic) {
std::cout << "special treatment of DA" << std::endl;
std::cout << "called from i: ";
f(t);
}
But it seems to do exactly what I want:
generic treatment of A
called from i: f A
special treatment of DA
called from i: f DA
special treatment of DA
called from i: f DDA
Even though it needs to be called in a weird way: i(a, &a); i(b, &b); i(c, &c);
Now I have several questions:
- Why the hell does this work?
- Do you think it is a good idea? Where are possible pitfalls?
- Which other ways of doing this kind of specialization would you suggest?
- (How do type conversions fit into the madness that is template partial ordering and such...)
I hope this was reasonably clear. :)