在以下代码中,foo<T>
和bar<T>
调用函数operator+
和someOtherFunction
,这些函数在模板化函数之后定义,但 之前,它们在main()
中实例化。
使用clang,这可以正常工作,除了bar<int>
。为什么不允许这样做? someOtherFunction(int)
在实例化时可见,对foo<S>
和bar<S>
来说似乎已足够。
template<typename T> void foo(T t) { (void)(t + t); }
template<typename T> void bar(T t) { someOtherFunction(t); }
struct S {};
// operator+(int, int) is built in
void operator+(const S& lhs, const S& rhs) {}
void someOtherFunction(int s) {}
void someOtherFunction(const S& s) {}
int main() {
foo(42); // works
foo(S()); // works
bar(42); // error: call to function 'someOtherFunction' that is neither visible in the template definition nor found by argument-dependent lookup
bar(S()); // works
return 0;
}
error: call to function 'someOtherFunction' that is neither visible in the template definition nor found by argument-dependent lookup someOtherFunction(t); ^ note: in instantiation of function template specialization 'bar<int>' requested here bar(42); ^ note: 'someOtherFunction' should be declared prior to the call site void someOtherFunction(int s) {} ^