C++ 类 Any:存储任意类型的值
#include
class Any { private: void* data; // 用 void* 指针储存任意类型的值 const std::type_info* type; // 储存值的类型信息
public: Any() : data(nullptr), type(&typeid(void)) {} // 默认构造函数,初始化为空值 ~Any() { delete data; } // 析构函数,释放动态分配的内存
Any(const Any& other) : data(other.clone()), type(other.type) {} // 拷贝构造函数
template<typename T>
Any(const T& value) : data(new T(value)), type(&typeid(T)) {} // 模板构造函数,用于传入具体类型的值
Any& operator=(const Any& other) { // 重载赋值运算符
if (&other == this) return *this;
delete data;
data = other.clone();
type = other.type;
return *this;
}
template<typename T>
Any& operator=(const T& value) { // 重载赋值运算符,用于传入具体类型的值
delete data;
data = new T(value);
type = &typeid(T);
return *this;
}
template<typename T>
T cast() const { // 类型转换函数,将储存的值转换为指定类型
if (typeid(T) == *type) {
return *static_cast<T*>(data);
}
throw std::bad_cast();
}
bool isEmpty() const { return data == nullptr; } // 判断是否为空值
private: void* clone() const { // 克隆储存的值 if (data != nullptr) { return type->clone(data); } return nullptr; } };
int main() {
Any a = 10;
std::cout << "a = " << a.cast
Any b = "Hello";
std::cout << "b = " << b.cast<const char*>() << std::endl;
a = b;
std::cout << "a = " << a.cast<const char*>() << std::endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pYty 著作权归作者所有。请勿转载和采集!