Boost logo

Boost Users :

From: Alexander Nasonov (yg-boost-users_at_[hidden])
Date: 2003-02-25 05:43:04


(Second attempt to post)

Matthew Dempsky wrote:
> I'm curious if there's any way to get code like the following to work:
>
> boost::any a = char(10);
> int i = boost::any_cast<int>(a);

You can customize boost::dynamic_any::any. Example:

#include <string>
#include <stdexcept>
#include <iostream>

#include <boost/mpl/list.hpp>
#include <boost/type_traits/is_convertible.hpp>

#include <boost/dynamic_any/any.hpp>
#include <boost/dynamic_any/function.hpp>
#include <boost/dynamic_any/operations.hpp>

// helper
template<bool IsConvertible>
struct convert_to_int
{
  template<class T>
  static int do_convert(const T & value)
  {
    int result = value;
    return result;
  }
};

template<>
struct convert_to_int<false>
{
  template<class T>
  static int do_convert(const T & value)
  {
   throw std::runtime_error(std::string("no convertion to int"));
  }
};

// any to int convertion
struct to_int
  : boost::dynamic_any::function<
      to_int, // curiously recurring pattern
      int (const boost::dynamic_any::arg &)>
{
  template<class T>
  int call(const T & value)
  {
      typedef convert_to_int<
        ::boost::is_convertible<T, int>::value> converter;
      return converter::do_convert(value);
  }
};

// customized any
typedef boost::dynamic_any::any<boost::mpl::list<
  to_int, boost::dynamic_any::to_ostream<char> > > my_any;

int main()
{
  my_any a('a');
  my_any b(3.14);
  std::cout << a << " -> " << to_int()(a) << '\n';
  std::cout << b << " -> " << to_int()(b) << '\n';
}

CVS access to the library:
$ cvs -d:pserver:anonymous_at_[hidden]:/cvsroot/cpp-experiment login
$ cvs -z3 -d:pserver:anonymous_at_[hidden]:/cvsroot/cpp-experiment
co dynamic_any

--
Alexander Nasonov
Remove - m y c o p from my e-mail address for timely response

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