嵌套类型的重载操作符
overloading operator for a nested type
下面的代码可以正常构建,但是没有调用重载的模板操作符。为什么呢?main()
函数打印120
而不是x
。
#include <iostream>
namespace foo
{
struct bar
{
enum Type { x = 'x', y = 'y' };
};
template<typename T> std::ostream& operator<<(std::ostream& s, typename T::Type o) { return s << char(o); }
}
int main()
{
foo::bar::Type t{ foo::bar::x };
std::cout << t;
}
编译器将永远无法确定T
类型应该是什么,以便实例化模板(查看此问题以了解更多信息)。只需这样做:
std::ofstream & operator<<(std::ostream & s, bar::Type t){...}
你声明的enum
对bar
是公共的,所以在这种情况下没有访问限制。