#include class any { public: any() : value(nullptr) {} template any(const T& val) : value(new holder(val)) {} any(const any& other) : value(other.value ? other.value->clone() : nullptr) {} ~any() { delete value; } any& operator=(const any& other) { if (this != &other) { delete value; value = other.value ? other.value->clone() : nullptr; } return this; } template any& operator=(const T& val) { delete value; value = new holder(val); return this; } template T cast() const { if (value) { return dynamic_cast<holder>(value)->data; } throw std::bad_cast(); } private: struct base_holder { virtual ~base_holder() {} virtual base_holder clone() const = 0; }; template struct holder : base_holder { holder(const T& val) : data(val) {} base_holder* clone() const { return new holder(data); } T data; }; base_holder* value; }; int main() { any a = 10; std::cout << a.cast() << std::endl; a = 3.14; std::cout << a.cast() << std::endl; try { std::cout << a.cast() << std::endl; } catch (const std::bad_cast& e) { std::cout << "Failed to cast to int" << std::endl; } return 0; }

C++ any 类实现:使用类型擦除存储任意类型的值

原文地址: https://www.cveoy.top/t/topic/pYtC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录