c++ - 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); }
但它没有做这项工作。
解决方案
case
应该使用常量表达式,即编译时常量。将您的运营商标记为constexpr
:
template<class T> inline constexpr T operator| (T a, T b){ return (T)((int)a | (int)b); }
推荐阅读
- kubernetes - 在 kubernetes 的 envoy 前使用 AWS 负载均衡器的最佳方式
- python - 从字典列表中删除字段
- flutter - 我将 Flutter 1.22.4 升级到 Flutter 2.0.1 但我的电脑上仍然没有网络支持
- html - jquery-ui 显示未捕获的类型错误
- sql - Athena 根据 S3 中引入的分区动态查询更改
- wordpress - 从 Bluehost 到 Godaddy 的 Wordpress 网站迁移
- c# - 如何将重复的 where 子句表达式从 linq 拉到函数中?
- java - 动态规划问题:最小化通过数组的路径
- angular - ionic 6 - ngFor 不显示数据 firebase 实时数据库
- javascript - 有效 JSON 的双引号转义