#include \n#include \n\nclass any {\npublic:\n any() : data(nullptr) {}\n \n template\n any(const T& value) : data(new holder(value)) {}\n \n any(const any& other) : data(other.data ? other.data->clone() : nullptr) {}\n \n ~any() {\n delete data;\n }\n \n any& operator=(const any& other) {\n if (this != &other) {\n delete data;\n data = other.data ? other.data->clone() : nullptr;\n }\n return this;\n }\n \n template\n any& operator=(const T& value) {\n delete data;\n data = new holder(value);\n return this;\n }\n \n template\n T cast() const {\n if (typeid(T) != data->type()) {\n throw std::bad_cast();\n }\n return static_cast<holder>(data)->value;\n }\n \nprivate:\n struct base_holder {\n virtual ~base_holder() {}\n virtual base_holder clone() const = 0;\n virtual const std::type_info& type() const = 0;\n };\n \n template\n struct holder : base_holder {\n holder(const T& value) : value(value) {}\n base_holder* clone() const override {\n return new holder(value);\n }\n const std::type_info& type() const override {\n return typeid(T);\n }\n T value;\n };\n \n base_holder* data;\n};\n\nint main() {\n any a = 10;\n std::cout << a.cast() << std::endl;\n \n a = 3.14;\n std::cout << a.cast() << std::endl;\n \n try {\n std::cout << a.cast() << std::endl;\n } catch (std::bad_cast& e) {\n std::cout << "Failed to cast to int" << std::endl;\n }\n \n return 0;\n}

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

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

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