<<
Https://godbolt.org/z/8bf1eawpq我最近在GCC-13上升级了我的操作系统(可能来自GCC-11)。以前没有错误。 首先,这可能看起来像是订单问题,但是操作员是由模板实例化的时间来定义的。
#include <ostream>
#include <iostream>
namespace ns {
struct Bar { int x; };
struct Foo { Bar bar; };
};
// Why does this fix things
#if 0
inline std::ostream& operator<<(std::ostream& os, const ns::Bar& bar);
inline std::ostream& operator<<(std::ostream& os, const ns::Foo& foo);
#endif
template<class T>
std::ostream& printer(std::ostream& os, const T& obj)
{
os << obj; // error: no match for 'operator<<'
return os;
}
// I do not own 'ns' but I want to make a generic printer for it
// Wrapping this in 'namespace ns {...}' is the solution, but why?
inline std::ostream& operator<<(std::ostream& os, const ns::Bar& bar)
{
return printer(os, bar.x);
}
inline std::ostream& operator<<(std::ostream& os, const ns::Foo& foo)
{
return printer(os, foo.bar);
}
void test()
{
ns::Foo foo;
std::cout << foo;
}
输出
foo.bar
,它需要在定义的地方输出
printer
operator<<
,没有用于'打印机后定义的输出运算符。如果您转发声明
bar.
并在输出操作员之后定义它,则一切都起作用。
printer