On Thursday, July 18, 2013 11:55:00 AM UTC-5, 8604spr...@googlemail.com wrote:
Does the order of template function overloads matter? In the
following code, I would expect both a() and b() to produce the same
output since both overloads of f() are visible at the point of
instantiation of both a() and b(). However, with gcc (both 4.7.2 and
4.8.1), the tuple overload is not chosen for a(). Why does this
happen?
It has to do with what is visible at the point of the function
definition. It's not even a template issue, nor a c++11 issue.
A much simpler, non c++11, non-template example:
#include <iostream>
void f( long ) { std::cout << "long\n"; }
void a( int t ) { f( t ); }
void f( int ) { std::cout << "int\n"; }
void b( int t ) { f( t ); }
int main( int, char *[] )
{
int x = 1.0;
a(x); // long
b(x); // int
}
a() only sees the f(long) function, and since int can be converted
to long, and it's the only choice, that's what a calls. However,
b sees both f(int) and f(long), and can pick a better match than a
can, because it has more choices.
Perhaps surprising at first, but it should be obvious that you don't
want arbitrary functions added later to change the meaning of
functions that are already defined. If it didn't behave this way, then
EVERY function you write would have the potential of changing the
meaning of other functions already written. (At least within the same
compilation unit.)
It is even worse than that. If we allowed latter declarations of
the place. A functions definition would become dependant upon what
overloads were present at the point of use. That way lies insanity.
and not just the source code file written by the programmer.
because template definitions are exposed in multiple TUs.
[ comp.lang.c++.moderated. First time posters: Do this! ]