如何将枚举类型作为接收非枚举引用参数的函数实参?
I2C驱动枚举类型与uint8_t引用转换问题
需求与限制
- 调整通用I2C读写函数,使其接收引用类型输入并返回
bool值用于错误处理 - 设备驱动代码中使用枚举类型替代魔数
- 限制条件:禁止使用
reinterpret_cast、不为枚举添加函数重载、不创建临时变量
示例代码
#include <iostream> #include <bitset> // i2cCommunication.h 通用I2C通信库头文件 // 该函数属于通用库,无法访问驱动中的枚举定义 bool read(uint8_t& input_ref) { if(!true) // 实际代码中此处会向I2C总线写入设备地址并检查应答 { return false; } input_ref = 0b01; // 实际代码中此处会从设备读取数据 return true; // 返回值由单独的读取状态函数决定 } // driver.h 设备驱动头文件 // #include "i2cCommunication.h" // 驱动中定义的增益等级枚举 enum GainLevel { GAIN1 = 0b00, GAIN2 = 0b01 }; GainLevel gain = GAIN1; bool updateGainLevel() { if(read(static_cast<uint8_t&>(gain))) { std::cout << std::bitset<8>(gain); // 仅用于示例输出 return true; } else { return false; } } // 主程序文件 // #include "driver.h" int main() { updateGainLevel(); return 0; }
报错信息
错误:从类型‘GainLevel’到类型‘uint8_t&’(别名‘unsigned char&’)的无效‘static_cast’转换
内容的提问来源于stack exchange,提问作者Brendan
相关产品推荐
相关产品推荐

