Boost logo

Boost :

From: George A. Heintzelman (georgeh_at_[hidden])
Date: 2001-07-05 09:39:14


Hi,

I've been using the any.hpp currently out there quite successfully for
a little while. There are two main complaints that I have with the
current implementation. The first is easy to fix: for those situations
where you know for some reason what type is contained in the any, you
should be able to cast it without the overhead of checking the typeid,
which can (fer ex, in gcc) involve an expensive string comparison. So I
add an 'unchecked_any_cast' as a friend:

    template <typename ValueType>
    ValueType unchecked_any_cast(const any & operand) {
      return static_cast<any::holder<ValueType> *>(operand.content)->
held;
    }

This is pretty dangerous, I'll grant, and if you screw it up you're
definitely into undefined-behavior land. Hence the long,
easily-greppable name. But I think that at least supplying this
capability will satisfy the pedal-to-the-metal sorts.

The second complaint is a little harder to deal with. I often store
fairly small objects in the any -- ints, floats, doubles, std::strings.
In these cases, the any is a pointer to an object the size of a
pointer, and involves unnecessary dynamic memory allocation. I would
like to see investigated an any implementation where the type is stored
in the object proper, and 'small' objects are likewise stored in the
objects. It seems like a no-brainer to store objects up to
sizeof(pointer) in the object proper (giving the any a
2*sizeof(pointer) on most implementations), but where to draw the line
is probably a question of the specific usage.

Right now, my application using the any-type is not particularly
CPU-bound, so I haven't had a strong impulse to attempt this myself,
but if any is moving towards official adoption into boost, I might be
talked into doing this myself.

Finally, I have one suggestion for longer range work. One use of the
any-type is in returning values from database queries, where the C++
code doesn't necessarily know what it will get back. In that context,
one will often get returned arrays of many objects of a single, unknown
type. It seems silly to store the type of these objects repeatedly.
Thus, it would be useful to have an any_array type as well, or perhaps
an any-adapter for STL containers, though some thought needs to go into
how to do that correctly.

George Heintzelman
georgeh_at_[hidden]


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk