(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
#include
#include
#include
#include
// 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::value> converter;
return converter::do_convert(value);
}
};
// customized any
typedef boost::dynamic_any::any > 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@cvs.sourceforge.net:/cvsroot/cpp-experiment login
$ cvs -z3 -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/cpp-experiment
co dynamic_any
--
Alexander Nasonov
Remove - m y c o p from my e-mail address for timely response