You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将枚举类型作为接收非枚举引用参数的函数实参?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 08:55:24