Boost logo

Boost :

From: Vladimir Prus (ghost_at_[hidden])
Date: 2005-02-16 03:44:42

Currently, boost::any supports two kinds of conversion:

1. Unchecked conversion to pointer (NULL is returned if conversion is
2. Checked conversion to value type (exception is thrown if conversion is

I'd like to have another variant -- checked conversion to reference. The
following code does not compile:

    boost::any a = 1;
    int& i = boost::any_cast<int&>(a);

There are two issues:

1. Documentation says:

    If passed a value or reference, it returns a copy of the value content if

But even if I change the above to

    boost::any a = 1;
    int i = boost::any_cast<int&>(a);

it does not compile. Docs are at least inaccurate.

2. Can we make the above work? I attach a patch which implements casting to
reference, and passes all the existing test. I'd like this behaviour because
currently program_options contains code such as:

 template<class T>
    variable_value::as() {
        T* r = boost::any_cast<T>(&v);
        if (!r)
            throw boost::bad_any_cast();
        return *r;

which is plain ugly. With the patch, the above can be written as

 template<class T>
    variable_value::as() {
        return boost::any_cast<T&>(v);

- Volodya

Boost list run by bdawes at, gregod at, cpdaniel at, john at