C++ 类型擦除 Any 类:实现任意类型存储、拷贝构造函数和类型转换
#include
class Any { private: struct Base { virtual ~Base() {} virtual Base* clone() const = 0; };
template<typename T>
struct Derived : public Base {
T value;
Derived(const T& value) : value(value) {}
Base* clone() const {
return new Derived<T>(*this);
}
};
Base* data;
public: Any() : data(nullptr) {}
template<typename T>
Any(const T& value) : data(new Derived<T>(value)) {}
Any(const Any& other) : data(other.data ? other.data->clone() : nullptr) {}
~Any() {
delete data;
}
Any& operator=(const Any& other) {
if (this != &other) {
delete data;
data = other.data ? other.data->clone() : nullptr;
}
return *this;
}
template<typename T>
Any& operator=(const T& value) {
delete data;
data = new Derived<T>(value);
return *this;
}
template<typename T>
T cast() const {
if (data) {
return static_cast<Derived<T>*>(data)->value;
}
throw std::bad_cast();
}
};
int main() { Any a(5); Any b = a; Any c; c = a;
std::cout << a.cast<int>() << std::endl;
std::cout << b.cast<int>() << std::endl;
std::cout << c.cast<int>() << std::endl;
return 0;
}
在上述代码中,Any类使用类型擦除的技术,通过一个基类指针data来存储任意类型的值。Base结构体是一个纯虚基类,提供了一个clone()函数,用于创建当前类型的副本。Derived结构体是Base的派生类,用于存储具体的值,并实现了clone()函数。Any类提供了默认构造函数、带参数的构造函数、拷贝构造函数、析构函数、重载赋值运算符以及类型转换函数cast()。
在main()函数中,首先创建了一个Any对象a,并将其值设置为5。然后使用拷贝构造函数创建了b对象,使用重载赋值运算符将a的值赋给了c。最后,通过cast()函数将Any对象转换为具体的类型并进行输出。
注意,该示例中使用了static_cast来进行类型转换,因此要求用户必须正确指定转换的目标类型,否则会产生未定义的行为。在实际使用中,可以根据需要进行类型检查或者使用其他更安全的类型转换方式。
原文地址: https://www.cveoy.top/t/topic/pYtB 著作权归作者所有。请勿转载和采集!