I'm having an odd problem, and am wondering why g++ 4.1.2 is behaving the way it does.
Stripped to its essentials:
#include <iostream>
template<typename T>
inline void f(T x) { std::cout << x*x; }
namespace foo {
class A {
public:
void f() const { f(2); }
};
}
The call to f(2)
fails because the compiler fails to match the template function f
.
I can make it work with ::f(2)
but I would like to know WHY this is necessary, since it's completely unambiguous, and as far as my (admittedly out of date) knowledge of the matching rules goes, this should work.
The compiler examines all scopes for a candidate, starting with the current scope. It finds a function named f
in the immediate scope, and there stops the search. Your template version is never examined as a candidate.
See Namespaces and the Interface Principle for a complete explanation.
Refer to C++03 section
3.4.1 Unqualified name lookup
In all the cases listed in 3.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed.
In your code sample the compiler finds a name f
in the current scope thus ending the unqualified name lookup but there is a mismatch in the prototypes of the functions and so you get an error.
Qualifying it with ::
makes it work because the name is then searched in the global namespace and the f
with the correct prototype is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With