|
Boost : |
From: Alexander Nasonov (alnsn_at_[hidden])
Date: 2002-08-30 14:18:52
David Abrahams wrote:
> I've never needed 'any', but a word of encouragement: I think your ideas
> are interesting, and I hope others will be responsive (hint, hint).
One more idea. If it's possible to implement is_less_comparable<T> (ie can
be two values of type T compared using less<T>?) then may be add operator<
(or specialize less) to any? Its definition is quite intuitive
// pseudocode
if(a1.type() != a2.type())
return a1.type().before(a2.type());
calculate type T from equation: typeid(T) = a1.type()
if(!is_less_comparable<T>::value)
return false;
else
{
const T & v1 = any_cast<const T &>(a1);
const T & v2 = any_cast<const T &>(a2);
return less(v1, v2);
}
You can use this feature to store anys in a map or set. But if you don't
provide operator< (or less) for some type X then you can only store one any
containing value of type X. Anyway, it shouldn't affect anys containig
values of other types because type check preceding value check in operator<
for any.
I think that ability to store anys in a map or set is so desired that
somebody already implemented less functor for existent boost::any (or only
dreamt about that:). Am I right?. I can imagine what is inside this
functor! Switch-based solution. Adding visitation support to any can
improve situation only a little: something like less_compare_visitor<A, B,
C> will be inside. Imagine how to maintain this code! That's evil!
Adding additional requirement for stored types to be less comparable can end
up with poor implementations of operator< for stored types:
bool operator<(const X &, const X &)
{
// I don't use map to store any, said implementor
// of X, why should I provide this function?!
return false;
}
Which will certanly confuse users of class X. Also evil!
My solution also is not perfect. It has (at least) one weakness: behaviour
for non less comparable types. You can just forget to implement this
operator< for some type X and then use X with for example set<any>. But
wait, you can also missed a type while, for example, defining a visitor.
And it's considered as your fault, not of designer of visitor library. It's
the best that designer can give you and its behaviour is well defined and
documented. The same, I think, can be applied to my proposal :)
-- Best regards, Alexander Nasonov e-mail account: alnsn e-mail server: mail.ru
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk