Re: operator<< for boost::any
On Sun, 9 Dec 2001, assaflavieatwork wrote:
If all you want to do is output the value inside the 'any' you can add a virtual member to the place_holder/holder classes (inside any's impl) that will output to a ostream&.
That is exactly my need
in place_holder: virtual ostream& write(ostream&) = 0;
You mean placeholder? I have added this declaration as a pure virtual function in the queries part. class placeholder { ... public: // queries ... virtual ostream& write(ostream&) = 0; };
in holder: ostream& write(ostream& o) { o << held; };
I have added the declaration in the derived class holder from the abstract base class placeholder template<typename ValueType> class holder : public placeholder { ... public: // queries ... ostream& write(std::ostream& os) { os << held; } public: // representation ValueType held; };
outside any: std::ostream& operator << (std::ostream& out, const any& value) { return value.write(out); };
I don't understand how this can work since the class any contains a pointer to an object of class placeholder. This object has a member function write but not the class any itself? I have another comment more general about the any class The declaration placeholder * content; in the any class might be public or private depending on the value of the value of the define BOOST_NO_MEMBER_TEMPLATE_FRIENDS. Is it safe? #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS private: // representation template<typename ValueType> friend ValueType * any_cast(any *); #else public: // representation (public so any_cast can be non-friend) #endif placeholder * content; };
But that of course means changing the any.hpp file which of course isn't something everyone is willing to do...
Why not including a simple overloading of the << operator?
Anyway, it won't help you if you want to read the any back from an istream. You'll have to write some type information to the stream or else you'll just interpret everything as a string.
I understand that but that is not what I want to do. Sincerely Patrick Guio
But that of course means changing the any.hpp file which of course isn't something everyone is willing to do...
Why not including a simple overloading of the << operator?
There is a trade-off. Making the changes to the "any.hpp" header will allow you to stream your classes. But it also constrains the types that can be placed within the "any" class. After the changes, you can only place those types that have operator<< defined into the "any" class. That is why you should perhaps rename your modified "any" class to avoid confusion with the original class. Johan __________________________________________________ Do You Yahoo!? Send your FREE holiday greetings online! http://greetings.yahoo.com
participants (2)
-
Johan Ericsson
-
Patrick Guio