Boost logo

Boost :

Subject: [boost] [any] New feature idea for boost.any
From: Andres B. (andres.b.dev_at_[hidden])
Date: 2009-12-28 19:50:44


Hello, i am Andrés, i am new in the boost world and i have an idea to
boost.any.

With the actual boost::any i can't do this:

boost::any any_var;
int i;
any_var = 10;
i = 1 + any_var;
double d;
// d = 1.0 + any_var; // throw: bad_any_cast, because any_var is int
any_var = 10.0;
d = 1.0 + any_var - 3.0; // now any_var is double

because are incompatible types. To solve this problem, we need add the
casting operator and add overload the global operators.

I wrote the code and actually have the global operators overloaded +, -, *,
/, %.
I don't know how write code to Boost, for this reason maybe has errors.

namespase boost {
    class any {
    //....
    public:
        // casting operators
        template <class ValueType>
        operator ValueType
        () const
        {
            return boost::any_cast<ValueType>(*this);
        }

        template <class ValueType>
        operator ValueType
        ()
        {
            return boost::any_cast<ValueType>(*this);
        }
        // arithmetic operators
        template <typename ValueType>
        ValueType operator+
        (const ValueType& t1) const
        {
            return (ValueType)(*this) + t1;
        }

        template <typename ValueType>
        ValueType operator-
        (const ValueType& t1) const
        {
            return (ValueType)(*this) - t1;
        }

        template <typename ValueType>
        ValueType operator*
        (const ValueType& t1) const
        {
            return (ValueType)(*this) * t1;
        }

        template <typename ValueType>
        ValueType operator/
        (const ValueType& t1) const
        {
            return (ValueType)(*this) / t1;
        }

        template <typename ValueType>
        ValueType operator%
        (const ValueType& t1) const
        {
            return (ValueType)(*this) % t1;
        }

    //...

    } // End any

    //...

    // Global operators
    template <class ValueType>
    ValueType operator+
    (ValueType t1, boost::any t2)
    {
        return t1 + (ValueType)(t2);
    }

    template <class ValueType>
    ValueType operator-
    (ValueType t1, boost::any t2)
    {
        return t1 - (ValueType)(t2);
    }

    template <class ValueType>
    ValueType operator*
    (ValueType t1, boost::any t2)
    {
        return t1 * (ValueType)(t2);
    }

    template <class ValueType>
    ValueType operator/
    (ValueType t1, boost::any t2)
    {
        return t1 - (ValueType)(t2);
    }

    template <class ValueType>
    ValueType operator%
    (ValueType t1, boost::any t2)
    {
        return t1 % (ValueType)(t2);
    }
}

If you like it or not, please tell me.

Excuse my English


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