|
Boost : |
From: Itay (itay_maman_at_[hidden])
Date: 2002-07-09 03:06:38
"Daryle Walker" <darylew_at_[hidden]> wrote in message
news:B94F9CF6.1242%darylew_at_mac.com...
> Is there a way to print a boost::any object? If would call the print
> operator (<<) of the contained object if it exists, or do nothing if the
> contained object doesn't have a print routine or if there is no contained
> object.
>
>
There are two different ways to achieve that, each with its own drawbacks:
a) Use a variant. It supports full value-semantics, but requires you to
explicitly state the set of acceptable types. This set is (probably...)
finitie so, theoretically speaking, you can replace any boost::any object
with a properly-parameterized variant object. In practice, this is not
always true since: (1) The set of types may be too large for your compiler
to handle. (2) Your program's dynamic nature makes it impossible for you to
keep track of which types are assigned into your generic container, hence,
maintaining a centralized list of all of these types becomes too difficult.
I think that (2) is the weaker argument of the two, due to this: once you
convert your boost::any objects to variants any offending assignment will
trigger a compile-time error, so most of the work is carried out by the
compiler, for you.
b) You can parametrize boost::any on a function object which will be used as
a 'visitor'. Obviously, this requires some minor modifications to any.hpp.
The downside is that boost::any's value semantics becomes incomplete: copy
assignments of two boost::any objects parametrized on two *different*
objects, are now illegal:
/* print_to_cout and print_to_file are two different functors */
any<print_to_cout> a1;
a1 = ...
any<print_to_file> a2;
a2 = ...
a1 = a2; /* illegal!!! */
Several months ago I posted some code which implements a template-based
visitor:
http://groups.yahoo.com/group/boost/files/Power_visitor/power_visitor.zip.
The library includes an alternative boost::any implementation which supports
this functionality. The whole process is explained in the docs.
>I guess this would be an application of a general visitor strategy. Hasn't
>someone else asked about that?
There was a "making any visitable" thread that went on several months ago
(~April).
There's also this discussion from last week:
http://lists.boost.org/MailArchives/boost/msg31450.php
-Itay
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk