Consider this piece of code:
#include <iostream>
#include <vector>
template<typename A>
void foo(A& a) {
std::cout << "the wrong foo" << std::endl;
}
template<typename A>
void do_stuff(A& a) {
foo(a);
}
template<typename X>
void foo(std::vector<X>& a) {
std::cout << "the right foo" << std::endl;
}
int main()
{
std::vector<int> q;
do_stuff(q);
}
Why is it calling the “wrong” foo? If the first declaration of foo is removed the right foo is called.
I am using gcc 4.6.3.
Update:
If functions are declared in the following order, the right foo is called.
template<typename A> void do_stuff(A& a) { ... }
template<typename A> void foo(A& a) { ... }
template<typename X> void foo(std::vector<X>& a) { ... }
The observed behavior is correct, as
foo(a)is a type dependent expression according to:and under 14.6.4 (Dependent name resoultion):
The “wrong”
foo()is picked because that’s the only one visible at the point of template definition, and the “right”foo()is not considered because it’s not in a namespace associated with the types of the function arguments.If you modify your code so that the “right”
foo()would be in an associated namespace, it would be picked instead of the “wrong”foo(). (In this particular case, it’s not allowed by the standard, so don’t do the below, but with your own namespace / types this is how it should work)