c++ - 我怎样才能修改我的 boost::any 类

标签 c++ class boost

我正在尝试实现 boost::any 类:

struct any
{
private:
struct holderBase
{
    virtual ~holderBase(){}
};

template<typename T>
struct holder : public holderBase
{
    T content;
    holder(const T& value) : content(value){}
    holder(const holder<T>& other) : content(other.content){}
};

holderBase *hl;
public:
template<typename T>
any(const T& data = T()) { hl = new holder<T>(data); }
any(const any& other) { hl = other.hl; }

template<typename T>
T get()
{
    if(holder<T>* p_hl = dynamic_cast<holder<T>*>(hl))
        return p_hl->content;
    else
        throw std::runtime_error("std::runtime_error");
}
};

我使用 holder 类(由 holderBase 继承)来存储数据。 如何修改 any::get() 函数(甚至修改整个代码),使其不需要模板参数(get() 函数)?

最佳答案

你可以这样做:

template<typename T>
T get(T *ptr);

类似于 C time 函数,您将返回结果,并将其存储在 ptr 中。

编辑:您还可以重写转换运算符:

template<typename T>
operator T()
{
   return get<T>();
}

这将隐含地做你想做的事。

关于c++ - 我怎样才能修改我的 boost::any 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10434514/

相关文章:

c++ - 使用 gcc 强制实例化对象

c++ - 缓存行对齐(需要在文章中说明)

c++ - 使用类的成员

c++ - boost::asio 写入大尺寸时挂起

c++ - 如何在 Eclipse CDT 中获取 C/C++ 程序的控制台输入

c++ - 纯虚继承、多重继承、C4505

linq - 如何使用 LINQ 从对象列表中获取唯一的属性列表?

java - 从类方法显示类对象

c++ - 停止 io_service 对象和 boost::asio::io_service::work

c++ - 是否可以确定 boost::basic 可锁定适配器当前是否已锁定?