Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template function matching in g++

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.

like image 431
Dov Avatar asked Dec 02 '22 04:12

Dov


2 Answers

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.

like image 101
icecrime Avatar answered Dec 03 '22 16:12

icecrime


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.

like image 21
Prasoon Saurav Avatar answered Dec 03 '22 16:12

Prasoon Saurav