自己尝试实现失败:
1.
template<class T>
class any
{
private:
T t;
public:
any(T t)
{
...
}
};
因为any需要加入到容器中, 因此不能采用模板参数的方式来实现
2.
class any
{
private:
std::type_info ti_;
void* p_;
public:
template<class T>
any(T t)
{
ti_ = typeid(t);
p_ = static_cast<void*>(new T(t));
}
};
采用这种方式的问题是如何调用T的析构函数?
下面是boost::any的解决方式, 很nice
class any
{
private:
placeholder* content;
public:
struct placeholder
{
virtual ~placeholder() {};
};
template<class value_type>
struct holder : placeholder
{
holder(const value_type & v) : value(v) {}
value_type value;
};
template<class T>
any(T t)
{
content = new holder<T>(t); //
这种保存T的方式很nice, 利用了基类不需要T的声明, 模板与多态结合
}
~any()
{
delete content;
}
};