Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-07-15 09:43:28


From: "Corwin Joy" <cjoy_at_[hidden]>
[...]
> Sure. The point is to have a seperate class from the basic "any" class
since
> it provides extra facilities but also places additional requirements on
the
> held object - e.g. that it be streamable.
[...]
> This does not at all defeat the purpose of supporting I/O. There any many
> times when you want to use "any" as a kind of prototype design where where
> you say that the type must is set by the initial construction and any
> further "writes" to that type must be cast into that type.

Could you please provide an example of such a design? This is quite
interesting.

FWIW, here's how I think the 'any' evolution should proceed:

Do not introduce separate concepts that add features. The reason is that an
important purpose of 'any' is to define 'typeless' interfaces, like variadic
functions:

void call_script_function(std::string name, std::vector<any> args);

Having an 'anyx' would lead to the common problem where you pass your anyx
to a library function (converting it to any), then that library hands you an
'any' back and you need a dynamic_cast-related facility to determine whether
this 'any' is an 'anyx' or not.

What I envision is this:

* support stream I/O:

#include <boost/any/iostream.hpp>

register_stream_inserter<int>();
register_stream_inserter<double>();
register_stream_inserter<std::string>();

register_stream_extractor<int>(/* regex */ "[\\+\\-]?[0-9]+", /* priority */
10);
register_stream_extractor<double>("[\\+\\-]?[0-9]+(\\.[0-9]*)?", 10);
register_stream_extractor<std::string>("[^ \r\n\t]+", 0);

// longest match wins, priority used to break ties

boost::any a;

while(std::cin >> a) // extraction fails on no match
{
    std::cout << a; // throws std::logic_error on no match
}

* support conversions:

#include <boost/any/conversions.hpp>

register_conversion<int, double>(rank_implicit);
register_conversion<double, int>(rank_diagnostic);
register_conversion<int, std::string>(rank_explicit,
my_conversion_int_string);

any a(1.0);

convert_to<int>(a); // returns 1, type int
convert_to<std::string>(a); // fails (std::bad_cast)

* support operators:

#include <boost/any/operators.hpp>

register_operator_plus<int>();
register_operator_plus<double>();
register_operator_plus<std::string>();

any a(1), b(1.4);

a + b; // returns any(2.4) since int->double ranks better than double->int

any("this") + any(" or that"); // returns any("this or that")

a += any("string"); // fails with std::logic_error, explicit conversions not
considered

Now we are very close to a simple but full-featured scripting language. :-)

What do you think? [The above can be implemented with no changes to
boost::any, I believe.]

--
Peter Dimov
Multi Media Ltd.

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