重载运算符的嵌套类型(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; }The following code builds fine but the overloaded template operator is not invoked. Why is that? The main() function prints 120 instead of 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是公开的,因此在这种情况下不必担心访问限制。
The compiler will never be able to figure what the type T is supposed to be in order to instantiate the template (check out this question for more on that). Just do this:
std::ofstream & operator<<(std::ostream & s, bar::Type t){...}The enum you declared is public to bar so there's no access restriction to have to worry about in this case.
更多推荐
发布评论