首页 > 解决方案 > C++ 重载 | 返回常量值的(按位或)运算符

问题描述

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

    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); }

但它没有做这项工作。

标签: c++

解决方案


case应该使用常量表达式,即编译时常量。将您的运营商标记为constexpr

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

推荐阅读