Boost logo

Boost :

From: ERICSSON,JOHAN (A-Sonoma,ex1) (johan_ericsson_at_[hidden])
Date: 2001-12-03 11:07:25


> -----Original Message-----
> From: johneddy_at_[hidden] [mailto:johneddy_at_[hidden]]
> Sent: Monday, November 12, 2001 3:51 AM
> To: boost_at_[hidden]
> Subject: [boost] any class
>
> The any class is very interesting. I find it very appealing for the
> purpose of mixed type containers. Is it necessary to poll the class
> for the actual type each time you wish to access the contents (or
> poll it for the type and supply the logic to deal with the results)?
>
> For instance, if I wish to print the value held by an "any" class
> object to the screen, must I do the following or is there a
> different/better way?:
>
> void Print(const boost::any& operand) {
>
> if(operand.type() == typeid(int))
> std::cout << any_ptr<int>(operand) << endl;
>
> else if(operand.type() == typeid(float))
> std::cout << any_ptr<float>(operand) << endl;
>
> else if ...
>
> }

One could easily create an "any" class with an operator<< implementation
that forwarded the call to whatever the contained type would do with an
operator<<. To do this: <WARNING UNTESTED CODE>
1. Add a virtual ostream& Print(ostream&)=0; method to the place_holder
class
2. Add the implementation in the holder<T> class to do something like this:
ostream& Print(ostream& out)
{
        out << held;
        return out;
}
3. Add an operator<< for the "any" class, making it a non-member friend
function. This function would simply forward the work to the Print() method
of the place_holder class.

---
Only thing is, you really don't have an "any" class now. Your class can only
contain types that support the use of operator<<. (You should name the class
as something else to remove any confusion)
You have a type constrained on a certain interface. It sounds like something
that virtual functions and derivations should be able to handle.
Unfortunately, since the operator<< is a non-member function of most types,
it can not be treated polymorphically. Otherwise, your best bet would be to
pass around an interface that documents the common methods of all the types
that implement it.
----
It would be cool if you could support something like operator<< for "any" at
run-time. It would allow you to add all types, (those that implement
operator<< and those that don't). It would throw a run-time error if you
tried to call operator<< on a type that didn't support it. I don't think
this can be supported using Standard C++, for the reasons that Michiel
gives. You would need some type of dynamic linking.
Johan

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