Re: template matching
Greg Herlihy wrote:
On Feb 8, 2:15 am, "assaf" <assafla...@gmail.com> wrote:
What should bar() output and why?
class Base {};
class Derived : public Base {};
template <typename T> void foo(const T&) { cout << "a"; }
template <> void foo(const Base&) { cout << "b"; }
void bar()
{
foo(Derived());
}
"a" is always printed. I want a specialization of foo that would
handle all descendants of Base, while all other types are handled by
the primary template function. Is that possible?
It is possible - by overloading foo():
template <typename T> void foo(const T&) { cout << "a"; }
void foo( Base & ) { cout << "b"; }
Now the the program will work as expected.
Only if you have a very out of date compiler. The compiler will
still instantiate foo<Derived>, and add it to the overload set.
Under the current rules (dating from the original C98 standard),
the template instantiation will be a better match, and will be
chosen over your overload. (IIRC, under the rules in the ARM,
a non-template function always beats a template one, and I think
many compilers did implement those rules before C98 was
adopted. I sort of think CFront 3.0.1 did, anyway. But I can't
find a compiler today which does, not even Sun CC 5.0 in mode
compat=4.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]