template <typename T>
T const& Max (T const& a, T const& b)
...{
return a > b? a : b;
}
class Any
...{
public:
class PlaceHolder
...{
public:
virtual const std::type_info & type() const = 0;
};
template<typename Ty>
class Holder
:public PlaceHolder
...{
public:
Holder(Ty const& data)
:_data(data)
...{
};
virtual const std::type_info & type() const
...{
return typeid(_data);
}
public:
Ty _data;
};
public:
Any()
:_holder(0)
...{
}
template<typename T>
Any(T const& ty)
:_holder(new Holder<T>(ty))
...{
cout<<"Con:"<<typeid(ty).name()<<endl;
}
template<typename T>
Any& operator=(const T& rh)
...{
if (!_holder)
...{
delete _holder;
}
cout<<"Op=:"<<typeid(rh).name()<<endl;
_holder = new Holder<T>(rh);
return *this;
}
const std::type_info & type() const
...{
return _holder ? _holder->type() : typeid(void);
}
~Any()
...{
delete _holder;
}
private:
template<typename ResultType>
friend ResultType* Any_cast(Any* operand);
PlaceHolder* _holder;
};
template<typename ResultType>
ResultType* Any_cast(Any* operand)
...{
return operand && (operand->type() == typeid(ResultType))
? &static_cast<Any::Holder<ResultType> *>(operand->_holder)->_data : 0;
}
main函数中:
vector<int> vo;
vo.push_back(1);
vo.push_back(2);
Any a = 5;
a = vo;
vector<int>* v = Any_cast<vector<int> >(&a);
for (vector<int>::iterator it = (*v).begin(); it != (*v).end(); ++it)
...{
cout<<*it<<endl;
}
2452



被折叠的 条评论
为什么被折叠?



