【发布时间】:2014-11-12 10:36:16
【问题描述】:
Boost::Any 使用通用基类placehoder,从中派生模板化holder 类。 placehoder 提供了一个带有虚方法的接口,特别是一种检索 any 所包含内容的 typeid 的方法。然后 any 包含一个指向 placeholder 的指针。我不明白的是placeholder的用途和虚方法的使用。让这个any 的简化构造(接口的源可用here):
class any
{
public:
template<typename ValueType>
any(const ValueType & value) : content(new holder<ValueType>>(value)) {}
private:
class placeholder
{
public:
virtual const std::type_info & type_info() const = 0;
};
template<typename ValueType>
class holder : public placeholder
{
public:
holder(const ValueType &value) : held(value) {};
virtual const std::type_info &type_info() const
{
return typeid(ValueType);
}
const value_type held;
};
placeholder *content;
}
在我看来,placeholder 可以完全删除,placeholder *content; 替换为 holder *content;。
此外,我不明白any 中使用的分配机制。让:
any & operator=(any rhs)
{
any(rhs).swap(*this);
return *this;
}
将any 分配给另一个。这将构造一个临时的any 与rhs 的content 和swap 它与当前对象,有效地做我们想要的但是......如果any 只是系统地,那么这一切的意义就在于构造一个新的临时any 并将其影响到当前对象以进行所有赋值操作?
【问题讨论】: