|
Boost : |
From: Corwin Joy (cjoy_at_[hidden])
Date: 2001-07-14 01:16:09
I would like to propose a couple of additions to the "any" library.
Proposal 1: A second "any" class which I will call anyx (for "any"
eXtractable). This is the same as the any class but with stream operators
i.e.
class anyx
{
public:
friend std::ostream & operator <<(std::ostream &o, const anyx &x)
friend std::istream & operator >>(std::istream &i, const anyx &x);
...skip the obvious implementation with virtual functions etc...
}
There are two reasons why this would be nice:
1. You often want to send a variant type to a stream or output.
2. If you really want a cast operator from any you can now get it via:
any a("3.1415");
double d = lexical_cast<double>(a);
The disadvantage of course is that the held type must support istream and
ostream operators for "anyx" to work.
Also, this lexical cast is pretty inefficient if you want to cast across
pure numeric types. It would be nice to have the equivalent of numeric_cast
working with any. Surprisingly, I think this can also be done. So, lets
say the numeric types you are using with any can be safely upcast to doubles
(if you have numeric types that can't be upcast to a double such as
arbitrarily long integers we can specialize the templated "holder" class to
upcast to some other type -- this implies that holder has to go outside the
"any" class since sub-class templates can't be specialized). Then, numeric
class might look like this inside any:
class any {
template<typename Target> Target numeric_cast(Target *dmy) {
// Step 1: Get numeric_limits for any "content", and the sign value
for content. Throw if these are not compatible with the target type.
// Step 2: upcast content to "root" type, e.g. double
// Step 3: downcast "root" type to Target
}
// There are some tricks in the above if you have multiple possible root
types - I can discuss if there is interest
Suggestion 2:
The current "any" is quite inefficient in that both the clone and the
constructor allocate with just a simple new. If you are using a lot of
"any" instances this is going to thrash the allocater & be quite
inefficient. I think it would be very nice to take advantage of the boost
pooled memory allocator here.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk