I noticed strange behavior regarding function search, relying on a function to be defined later:
#include <iostream> template <typename T> void foo(const T&) { std::cout << "Basic" << std::endl; } template <typename T> void bar() { T x; foo(x); } void foo(const int& x) { std::cout << "int:" << x << std::endl; } int main() { bar<int>(); }
Output:
Basic
For some reason, I was expecting foo be used inside bar to find the overload below it. Moving the foo overload above bar makes the output int:0 (or just writing the declaration) desired.
The same behavior does not seem to apply to binary operator overloading:
#include <iostream> struct Foo {} foo; template <typename T> void operator<<(const Foo&, const T&) { std::cout << "Basic" << std::endl; } template <typename T> void bar() { T x; foo << x; } void operator<<(const Foo&, const int& x) { std::cout << "int:" << x << std::endl; } int main() { bar<int>(); }
Output:
int:0
I have two questions: first, why is this behavior and why is it different from operator overloading? Second: if I have a named function (e.g. using foo ), is there a way to write the bar function in such a way as to detect an overloaded foo , declared later in the translation block?
source share