Am struggling a lot to find how to do to use boost::any
to create a print function that can print any type using template first.
template <typename T>
struct printer {
void print(ostream& os, const boost::any& a);
};
I need to define first print()
.
i wish to have the real operator <<
for any, The idea is simple: attach to each any object an instance of class
printer<T>
with the suitable T and change this object when the value type of the any
changes.
A first technical problem is that the printer object depends on T whereas any is not (and should not be) a class template.
Please I really need a hand is for tonight or tomorrow I have a deadline for tomorrow but I wish to work on it tonight.
I do it like this, which I think is clean and safe:
any_extension.hpp:
any_extension.cpp:
For any type that you'd like supported, simply ensure that AnyWriter::register() has been called for its type and an operator<< exists for it.
For example:
any_test.cpp:
output: cluck!
There is quite easy way to do this, described in "Beyond the C++ Standard Library: An Introduction to Boost":
and then you use
any_out
instead ofboost::any
.Check out this thread on the Boost mailing list: http://lists.boost.org/Archives/boost/2005/01/79232.php
It has a few ideas, some of which seem sort of OK and some of which don't (to me). Overall, though, this seems like a difficult task to accomplish in a general way, since (as mentioned in that thread), some types will never be ostream'able, yet could be contained in a
boost::any
object.Very nice answer by Pawel Zubrycki (mentioning Björn Karlsson's book).
But the code has a few errors in the following lines:
Here's a corrected version of Pawel Zubrycki's answer that works (partially...)
This test-code works:
However!!!!
The following does not work:
Here nothing gets printed.
Why??
Well the type is messed up, in the following constructor
if we then instantiate streamer as
Removing the reference from the constructor, i.e.
... is one solution.
Another solution is to leave the reference and tweak the template instantiation of
streamer_impl
. See belowWhich brings as to the following recommened solution is:
The test-code that gave some trouble above, now works nicely (with the "recommeded solution"):