小编Kon*_*nvt的帖子

如何修复“Any”类代码以正确输出数据?

我正在尝试模拟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)

c++ templates std template-meta-programming c++17

2
推荐指数
1
解决办法
65
查看次数

标签 统计

c++ ×1

c++17 ×1

std ×1

template-meta-programming ×1

templates ×1