考虑一下我在IBM网站上找到的这个例子:
#include <iostream>
using namespace std;
void f(double) { cout << "Function f(double)" << endl; }
template<class T> void g(T a) {
f(123);
h(a);
}
void f(int) { cout << "Function f(int)" << endl; }
void h(double) { cout << "Function h(double)" << endl; }
void i() {
extern void h(int);
g<int>(234);
}
void h(int) { cout << "Function h(int)" << endl; }
int main(void) {
i();
}
它会打印什么?
The IBM documentation I adapted this example from, available here, says it will print:
Function f(double) Function h(double)
The rationale for this is that template-parameter-dependent name lookup is performed right before the instantiation of
i()
, so it findsh(double)
but noth(int)
.When I compile it using GCC 4.4.1, it prints:
Function f(double) Function h(int)
GCC seems to be looking up the template-parameter-dependent names in the template after everything else has been compiled, so it finds both
h(double)
andh(int)
, and prefers the latter.When I compile it using Clang 2.8, it fails to compile. The compiler error is:
ibm_example.cc:8:3: error: use of undeclared identifier 'h' h(a); ^ ibm_example.cc:16:3: note: in instantiation of function template specialization 'g<int>' requested here g<int>(234); ^ 1 error generated.
Clang seems to be looking up the template-parameter-dependent names in the template at the point where the template is declared, so it finds neither
h(double)
norh(int)
.
哪一个是正确的?