On May 11, 7:39 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
desktop wrote:
But is that the only difference? Are the types decided at compile time
in both examples etc?
No. If your code never makes use of 'mytemp(int)' or 'mytemp(double)',
the code for them will never be generated. I heard a rumour that today
linkers can detect that a [regular] function is not used and throw its
code out, but I would have to see it to believe.
Put them in a separate compilation unit, put the results in a
library, and I don't know of a linker which won't incorporate
just the functions it needs. VC++ has an option to support this
even if the functions aren't in separate compilation units, but
I'm not sure whether it is such a good idea.
Yes, involvement of conversions is the main reason to prefer regular
[overloaded] functions over template specialisations. If you happen
to use mytemp(blah), and 'blah' is 'short', an overloaded function
'mytemp(int)' will be used, whereas 'mytemp<int>(int)' will never be
picked (and the default case will be then used). Same if 'blah' is
'float' -- the 'mytemp<double>' specialisation isn't applicable.
Also, your example contains 3 overloaded functions and 4 functions
based on the template (one generic and three specialised). They are
not exactly equivalent.
That's the big difference, of course. If you have a template,
the compiler will do type deduction on it. If it succeeds, the
results will be added to the overload set. If it fails, they
won't be.
In his first example, the results would have been more or less
the same if he had provided overloaded functions, rather than
template specializations. The template function declaration
would be instantiated, but any time it corresponded to an
overloaded non-template function, that function would be chosen
instead.
There is one big difference, however: you can force the function
you want using templates, by explicitly specifying the template
arguments, e.g.:
mytemp< int >( someDouble ) ;
Of course, explicitly casting the argument to the targeted type
has almost the same results: the only difference is if the
conversion uses an explicit constructor, in which case casting
the argument works, but the above would fail.
--
James Kanze (Gabi Software) email:
ja*********@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