嵌套类型的重载操作符

overloading operator for a nested type

本文关键字:操作符 重载 嵌套类型      更新时间:2023-10-16

下面的代码可以正常构建,但是没有调用重载的模板操作符。为什么呢?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){...}

你声明的enumbar是公共的,所以在这种情况下没有访问限制。