|
Boost : |
From: Jorge Lodos (lodos_at_[hidden])
Date: 2006-04-24 12:23:40
Hi
The following is a partial solution for boost::any operations, including
operator==.
Adding the operator ValueType& as follows:
template <typename ValueType>
operator typename ValueType&() const
{
if (empty() || type() != typeid(ValueType))
boost::throw_exception(bad_any_cast());
return static_cast<any::holder<ValueType> *>(content)->held;
}
This is different from any_cast in that it returns a reference, instead of a
copy. Note also that this will never be used implicitely, you have to call
operator ValueType&() explicitely.
Operations with values can be added as:
template <typename ValueType>
bool operator==(const ValueType& rhs)
{
return rhs == this->operator ValueType&();
}
Or
template <typename ValueType>
any& operator+=(const ValueType& rhs)
{
this->operator ValueType&() += rhs;
return *this;
}
All operators could be added this way.
While this won't break existing code and allows for any object operations,
it still has the following drawbacks:
1. No type conversion is performed, (due to template argument deduction).
Thus a float can be compared or added to another float, but not to a long,
for instance.
2. No operations between any objects can be performed, only between an any
and a concret object.
3. The order matters. 0 == any(0) won't compile, while any(0) == 0 will do.
4. It is easy to forget that all operations may throw.
If you have any idea of how to overcome (or improve) any of these please let
me know.
By the way, I'm testing with VC 8.0 and the program compiles and behaves
identically calling operator ValueType&() or operator ValueType() with the
above declaration. Is that correct?
Cheers
Jorge
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk