'`std::cout << FooStuff::Foo();` chooses completely unrelated overload instead of exactly matching one
I have this code:
#include <iostream>
namespace FooStuff
{
struct Foo { };
}
decltype(std::cout)& operator << (decltype(std::cout)& left, const FooStuff::Foo& right)
{
return left;
}
void test1()
{
// This works fine
std::cout << FooStuff::Foo();
}
As far as I can tell, this is the best operator << that one could possibly write down to match the call in test1, and it works as you would expect.
Now add this code below the code above:
namespace BarStuff
{
struct Bar { };
// Danger zone
void test2()
{
// This works too, for now
std::cout << FooStuff::Foo();
}
}
The call in test2 works too, as you would expect.
But if I insert the following operator right below the "Danger zone" comment, everything breaks:
Bar operator << (Bar left, Bar right)
{
return left;
}
Now the call in test2 won't compile because the compiler chooses the completely inappropriate overload that takes a bunch of Bars, even though the operator from the first snippet should be a perfect match:
main.cpp:33: error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'FooStuff::Foo')
(A ton of unrelated overloads omitted for brevity)
main.cpp:25: candidate function not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'BarStuff::Bar' for 1st argument
What the poop is going on? Why does the compiler choose that overload instead of the one I want it to choose?
And why does the error disappear, if Foo is moved outside FooStuff?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
