#include <iostream>
#include <type_traits>
// 定义一个枚举类型来表示存储的数据类型
enum class DataType {
INT,
LONG,
DOUBLE
};
// 使用匿名联合体实现数据存储
union DataUnion {
int intValue;
long longValue;
double doubleValue;
};
// 定义数据结构
struct DataStorage {
DataType type;
DataUnion data;
// 存储整型数据的函数
void store(int value) {
type = DataType::INT;
data.intValue = value;
}
// 存储长整型数据的函数
void store(long value) {
type = DataType::LONG;
data.longValue = value;
}
// 存储双精度浮点型数据的函数
void store(double value) {
type = DataType::DOUBLE;
data.doubleValue = value;
}
// 读取数据的函数,使用模板元编程确保类型安全
template<typename T>
T read() const {
static_assert(std::is_same<T, int>::value ||
std::is_same<T, long>::value ||
std::is_same<T, double>::value,
"Unsupported data type for read");
if (std::is_same<T, int>::value && type == DataType::INT) {
return data.intValue;
} else if (std::is_same<T, long>::value && type == DataType::LONG) {
return data.longValue;
} else if (std::is_same<T, double>::value && type == DataType::DOUBLE) {
return data.doubleValue;
}
throw std::runtime_error("Type mismatch during read");
}
};
int main() {
DataStorage storage;
storage.store(10);
std::cout << "Stored int value: " << storage.read<int>() << std::endl;
storage.store(1000000000000LL);
std::cout << "Stored long value: " << storage.read<long>() << std::endl;
storage.store(3.14159);
std::cout << "Stored double value: " << storage.read<double>() << std::endl;
return 0;
}
- 枚举类型
DataType
:用于标识当前存储的数据类型。
- 匿名联合体
DataUnion
:实际存储不同类型数据的地方。
- 结构体
DataStorage
:包含数据类型标识和联合体成员。
- 存储函数
store
:根据传入的数据类型存储相应的值,并设置类型标识。
- 读取函数
read
:使用模板元编程确保读取的数据类型与存储的类型一致,避免类型错误。在 main
函数中演示了如何使用这些函数进行数据的存储和读取。