Boost logo

Boost Users :

Subject: [Boost-users] boost:any/boost::variant for integral/floating type
From: Mathieu Malaterre (mathieu.malaterre_at_[hidden])
Date: 2010-06-01 09:12:43


Hi,

  I am looking at boost::any and boost::variant which seems to be very
usefull additions to C++ for building heterogenous containers.
  However in my case I need to build something that would be:
- type safe
- can only contains integral/floating type
- allow operations such as max() / min()

My typical operation on this 'generic_value_type' is simply `+= 1`.
boost::any seems difficult to use, since you need to call any_cast any
time you want to operate on the value.

I am thinking I could just wrap boost::variant inside a custom class,
and add my missing functionalities, something like:

struct AttributeValue
{
private:
  struct add_one_visitor
    : public boost::static_visitor<>
    {
    template <typename T>
      void operator()(T & i) const
        {
        i++;
        }
    };
  struct get_min_visitor
    : public boost::static_visitor<>
    {
    template <typename T>
      T operator()(T & i) const
        {
        return std::numeric_limits<T>::min();
        }
    };

public:
  AttributeValue& operator++() {
    boost::apply_visitor( add_one_visitor(), Value );
    return *this;
  }
  AttributeValue min() {
    return boost::apply_visitor( get_min_visitor(), Value );
    }
  boost::variant<double, char, int> Value;
};

Did I miss anything in boost ? Is boost::variant my best option (when
only using fundamental types) ?

Thanks

-- 
Mathieu

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net