我正在尝试模拟std::any,我的想法是使用基类指针指向不同类型的模板派生类,来实现存储不同类型数据的功能,比如std::any;因此我写了以下代码:
class Any {
TypeBase *_ptr;
public:
Any(): _ptr(nullptr) {}
Any(const Any &other): Any() { _ptr = other._ptr->copy(); }
Any(Any&& _other): Any() {
_ptr = _other._ptr;
_other._ptr = nullptr;
}
template<typename T> Any(T&& _data): Any() {
/*
* this function attempts to capture rvalue param
*/
_ptr = new Container<T>(std::forward<T>(_data));
}
~Any() { delete _ptr; }
template<typename T> T& data_cast() const {
if (_ptr == nullptr)
throw std::runtime_error("Container empty");
return static_cast<Container<T>*>(_ptr)->data;
}
};
Run Code Online (Sandbox Code Playgroud)
这些工具包类是:
struct TypeBase …Run Code Online (Sandbox Code Playgroud)