I noticed strange behavior regarding function lookup when 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 expected the use of foo
inside bar
to find the overload below it. Moving the overload of foo
to above bar
makes the output the desired int:0
(or just writing a declaration).
This same behavior does not appear to apply to overloading a binary operator:
#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, the first is: Why is the behavior like this and why is it different for operator overloading? The second is: If I have a named function (like my use of foo
), is there a way to write a function bar
in such a way to discover overloaded foo
s declared later in a translation unit?