#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;
}