|
From: stephan b. <st...@s1...> - 2005-01-20 21:45:23
|
On Thursday 20 January 2005 04:41, Marc Duerner wrote:
> I just had the idea that one could unify P::Util::Any and
> P::Util::Variant. They do basically both the same, but Any uses
> typeid and casting, while Variant (the class formerly known as LexT)
> uses stream based conversion.
Personally i would prefer to keep Variant and Any separate. They are
conceptually very similar, but in usage they are MUCH different beasts
and give much different guarantees regarding casts. Variant does use
any casting, for example, whereas Any *relies* on casting.
> template <typename ValueType>
> ValueType convertTo(const ValueType& defVal = ValueType()) const {
> Any::holder<ValueType>* valHolder = 0;
> valHolder = dynamic_cast< Any::holder<ValueType>* >(m_data);
> if(valHolder) {
> return valHolder->value();
> }
>
> ValueType retVal(defVal);
> std::stringstream ss;
> m_data->output(ss);
> ss >> retVal;
> return retVal;
This code will only compile if ValueType is i/ostreamable, which is
almost guaranteed to NOT be the case for many uses of Any.
> The dynamic_cast is a short cut.
It's not always syntactically possible to consolidate such type-based
shortcuts in the same code, without using middle-man template classes
and dispatching the different handlers via template specializations.
For example:
template <class T>
void foo( const T & )
{
... we'll see the body in a moment...
}
Obj * o = new Obj;
foo( o ); // legal
Obj o2;
foo( o2 ); // also legal
Now what should the body of foo() look like?
Imagine that we need to do this:
if( T is a pointer type ) { delete t; }
else { do nothing; }
that can't be syntactically consolidated in the same code. Won't compile
because delete t is not valid when T is not a pointer type.
> Does anybody see a problem with this?
Technically i must admit, i don't see a major problem with it.
"Internally", though, i would prefer to keep the distinction between
lexically castable types and "any" type, mainly because of the
guarantees each can/cannot provide.
--
----- st...@s1... http://s11n.net
"...pleasure is a grace and is not obedient to the commands
of the will." -- Alan W. Watts
|