模板化函数的实例化无法解析另一个函数

时间:2017-02-07 21:13:39

标签: c++ templates overloading overload-resolution

在以下代码中,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) {}
     ^

0 个答案:

没有答案