我正在为 Arduino 编写
std::variant
的类似物,我需要使用一个函数从 union is struct 中获取值,就像我使用 setValue
一样。
enum class ValueType : uint8_t {
BOOL,
FLOAT,
INT8_T,
INT16_T,
INT32_T,
UINT8_T,
UINT16_T,
UINT32_T
};
struct Variant {
union Value {
bool bool_value;
float float_value;
int8_t int8_value;
int16_t int16_value;
int32_t int32_value;
uint8_t uint8_value;
uint16_t uint16_value;
uint32_t uint32_value;
};
Variant(ValueType vType) : type(vType){};
void set_value(bool value_new) { value.bool_value = value_new; };
void set_value(float value_new) { value.float_value = value_new; }
void set_value(int8_t value_new) { value.int8_value = value_new; }
void set_value(int16_t value_new) { value.int16_value = value_new; }
void set_value(int32_t value_new) { value.int32_value = value_new; }
void set_value(uint8_t value_new) { value.uint8_value = value_new; }
void set_value(uint16_t value_new) { value.uint16_value = value_new; }
void set_value(uint32_t value_new) { value.uint32_value = value_new; }
const bool& get_bool_value() const { return value.bool_value; }
const float& get_float_value() const { return value.float_value; }
const int8_t& get_int8_value() const { return value.int8_value; }
const int16_t& get_int16_value() const { return value.int16_value; }
const int32_t& get_int32_value() const { return value.int32_value; }
const uint8_t& get_uint8_value() const { return value.uint8_value; }
const uint16_t& get_uint16_value() const { return value.uint16_value; }
const uint32_t& get_uint32_value() const { return value.uint32_value; }
private:
Value value;
ValueType type;
};
我不明白如何使用
get_value
来专门化功能ValueType type
,以免每种类型使用不同的功能。