|
Boost Users : |
From: Seishi Onishi
Date: 2002-12-16 21:27:27
I'm using a collection of boost::any for the variable container class
which has this map member.
std::map<std::string, boost::any> m_collection;
As you imagine, the container class can keep anything even the
container class itself recursively. You know, an boost::any may hold
copy expensive object. So I need a method to get the reference of the
value held in boost::any not to make the expensive copy. But I found
that the current any_cast implementation was not well support the
reference.
Issue 1: The following code causes compiler error on VC6&7.
boost::any dany = double(1.2);
double& rd = boost::any_cast<double>(dany);
Issue 2: The following code works but one copy constructer called.
class Foo foo;
boost::any fany( foo );
class Foo& rfoo = boost::any_cast<class Foo>(fany);
Actually, I found the way to sneak out of the issues.
double& rd = *boost::any_cast<double>(&dany);
class Foo& rfoo = *boost::any_cast<class Foo>(&fany);
But the problem is these codes won't throw bad_any_cast.
And I also wonder this *any_cast usage may not be the way the
developer supposed. So I expect that the current any_cast code will
be changed to well support the reference access.
It can be,
template<typename ValueType>
const ValueType& any_cast(const any & operand)
{
const ValueType * result = any_cast<ValueType>(&operand);
if(!result)
throw bad_any_cast();
return *result;
}
template<typename ValueType>
ValueType& any_cast(any & operand)
{
ValueType * result = any_cast<ValueType>(&operand);
if(!result)
throw bad_any_cast();
return *result;
}
-Seishi
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