[英]Overloading operator<< for enum class inside template class
我似乎无法为模板类中的枚举类重载operator<<
:
#include <iostream>
template <typename T>
struct S
{
enum class E { A, B };
E e;
};
template <typename T>
std::ostream& operator<<(std::ostream& s, const typename S<T>::E e)
{
return s << static_cast<int>(e);
}
int main()
{
const S<int> s {};
std::cerr << s.e; // error
}
Visual Studio 2015 产生的确切错误消息是:
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const S<int>::E' (or there is no acceptable conversion)
gcc 和 clang 都失败并显示类似的错误消息。
两个注意事项:
T = int
使用operator<<
重载,则代码也可以很好地编译。我错过了什么?
您的运算符模板无法推导出T
因为它在::
之前使用(考虑特化S
可能对类型S::E
做什么)。 使用无作用域枚举时,您将通过隐式转换为整数获得标准重载之一。
这里通常的方法是将操作符定义为(非模板)朋友。 然后重载决议,而不是模板参数推导,负责在其中进行选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.