C++重载|(按位OR)运算符,返回常数值

C++ Overloading | (bitwise OR) operator that returns constant value

本文关键字:运算符 返回 常数值 OR 重载 按位 C++      更新时间:2023-10-16

我想以以下方式使用运算符"|":

switch(color){
case Color::Red | Color::Green:
...

问题是运算符必须返回常数值,但我无法使其工作。我试过这样的东西:

template<class T> inline const T operator| (T a, T b){ return const (T)((int)a | (int)b); }

但它不起作用。

case应该使用常量表达式,即编译时常量。将您的操作员标记为constexpr:

template<class T> inline constexpr T operator| (T a, T b){ return (T)((int)a | (int)b); }