我有一个用于与 I2C 设备接口(读/写)的库,另一个库充当特定 I2C 设备的驱动程序。我试图在这里做两件有些独立的事情:
总的来说,感觉应该有更好的方法来做到这一点,所以我正在寻找关于如何在不使用reinterpret_cast的情况下做到这一点同时仍然实现目标的任何建议。我不想为枚举添加重载,并且希望避免创建临时变量。
当我尝试将设备寄存器读入声明为枚举类型之一的变量时,我收到几种有关无法在枚举和其他类型之间转换的错误。我认为能够使其与reinterpret_cast一起使用,但我的印象是应该尽可能避免这种情况。
我将我的真实程序浓缩为一个代表性示例,如下所示。
#include <iostream>
#include <bitset>
// i2cCommunication.h GENERIC I2C COMMUNICATION FILE
// This function is part of a generic library that cannot see the enum definition
bool read(uint8_t& input_ref)
{
if(!true) // This would be where you write the device address to the I2C bus and see if it was acknowledged
{
return false;
}
input_ref = 0b01; // This would be where you actually read from the device
return true; // This bool would be set by a separate function that reports read status
}
// driver.h DEVICE DRIVER FILE
// #include "i2cCommunication.h"
// This enum is defined in a header for a device "driver"
enum GainLevel
{
GAIN1 = 0b00,
GAIN2 = 0b01
};
GainLevel gain = GAIN1;
bool updateGainLevel()
{
if(read(static_cast<uint8_t&>(gain)))
{
std::cout << std::bitset<8>(gain); // Only here for the example
return true;
}
else
{
return false;
}
}
// MAIN FILE
// #include "driver.h"
int main()
{
updateGainLevel();
return 0;
}
错误如图:
error: invalid 'static_cast' from type 'GainLevel' to type 'uint8_t&' {aka 'unsigned char&'}
您可以使用
read
类型的局部变量调用uint8_t
,然后使用static_cast
将其分配给gain
:
bool updateGainLevel()
{
uint8_t g;
if (read(g))
{
gain = static_cast<GainLevel>(g);
std::cout << std::bitset<8>(gain); // Only here for the example
return true;
}
else
{
return false;
}
}