重载运算符的嵌套类型(overloading operator for a nested type)

编程入门 行业动态 更新时间:2024-10-28 18:32:09
重载运算符的嵌套类型(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.

更多推荐

本文发布于:2023-08-06 17:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   运算符   类型   overloading   nested

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!