如何重载枚举的<<运算符
How to overload the << operator for enums
我正在尝试为按位<<运算符编写一个通用模板重载,但我很难指定运算符的左侧是枚举,并且编译器给了我一个"不明确的重载"错误。
我希望static_assert会告诉编译器"file <<x"中的<<运算符不是我定义的模板,然后它会选择iostream中定义的<<运算符。但是,我收到一条编译器消息,说两者是模棱两可的。
它没有"cout <<x"的问题。
#include <fstream>
#include <iostream>
using namespace std;
enum DAY{MON=1,TUES=2,WED=4,THUR=8,FRI=16};
template<typename Enum>
constexpr Enum operator <<(Enum e,int n)
{
static_assert(std::is_enum<Enum>::value,
"template parameter is not an enum type");
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> ( static_cast<underlying>(e) << n );
}
int main()
{
// this does as I'd like
DAY day = MON;
day = static_cast<DAY>(day << 2); // this is the behavior I need
cout << day << endl;
// but this is ambiguous
ofstream file("test.dat");
float x;
file << x; // this line is ambigous
return 0;
}
static_assert
应用太晚,无法从过载分辨率中删除operator<<
。 您需要改用 SFINAE。 像这样的事情会做你想做的事:
template <typename Enum>
constexpr std::enable_if_t<std::is_enum_v<Enum>, Enum>
operator<<(Enum e, int n)
{
using underlying = typename std::underlying_type_t<Enum>;
return static_cast<Enum> ( static_cast<underlying>(e) << n );
}
现场演示
相关文章:
- 如何正确实现和访问运算符的各种自定义枚举器
- 标准::可选枚举的比较运算符
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 隐式不是带有枚举解释的运算符 (!)?
- 枚举和二进制或运算符(MISRA C++ 2008,4-5-2)
- 重载 std::字符串运算符+ 用于打印枚举名称
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 枚举类上的运算符+,起始值不为零
- 重载输入 (>>) 运算符以获取枚举字符串
- 枚举后位运算符上的重载相等运算符
- 枚举运算符不工作
- 枚举的复合赋值运算符真的应该根据其关联的算术运算符来定义吗?
- 枚举增量的运算符重载
- 类中枚举类的运算符重载
- C++11 类中放置的枚举类的重载运算符
- 根据运算符中的枚举值推断类型
- 如何重载枚举的<<运算符
- 枚举类型的重载>>运算符(工作日)
- 为什么可以使用范围运算符和类 A 名称在类 B 中访问类 A(公共)中的枚举
- 模板化 QDataStream 运算符<<用于枚举