我正在尝试重新创建在any
中找到的那个,Boost::any
并且我已经构建了三个类,但是,每当我找到reinterpret_cast
给定的值时,输出完全不同,只会扔掉垃圾。下面是我的代码:
namespace Types {
class PlaceMaker {
public:
PlaceMaker() { };
virtual ~PlaceMaker()
{
}
virtual PlaceMaker * clone()
{
return 0;
}
virtual const std::type_info & type() const = 0;
protected:
};
template<typename T>
class holder : public PlaceMaker {
public:
holder(const T & value)
: held(value)
{
}
virtual const std::type_info & type() const
{
return typeid(T);
}
virtual PlaceMaker * clone() const
{
return new holder(held);
}
T retrunHeld() const {
return held;
}
public:
T held;
//holder &operator=(const holder &) const = 0;
holder & operator=(const holder &) { }
};
class Any : PlaceMaker {
public:
Any() : maker(0) { };
template<typename ValueType>
Any(const ValueType & value)
: maker(new holder<ValueType>(value))
{
}
Any(const Any & other)
: maker(other.maker ? other.maker->clone() : 0)
{
}
Any& swap(Any &rhs) {
std::swap(maker, rhs.maker);
return *this;
}
template<typename ValueType>
Any & operator=(const ValueType & rhs)
{
Any(rhs).swap(*this);
return *this;
}
Any & operator=(Any rhs)
{
rhs.swap(*this);
return *this;
}
bool empty() const
{
return !maker;
}
const std::type_info & type() const
{
return maker ? maker->type() : typeid(void);
}
template<typename T>
T& cast() {
T* r = reinterpret_cast<T*>(maker);
return *r;
}
public:
PlaceMaker * maker;
};
主要我有以下内容:
int main() {
Types::Any a = 10;
std::cout << a.cast<int>();
}
// output: 96458224
谁能告诉我哪里出错了?
谢谢