|
Boost : |
From: Mark Coletti (mcoletti_at_[hidden])
Date: 2003-05-19 17:16:17
I'm trying to essentially do a dynamic_cast to an ABC parent class
with a child class stored in a boost::any object. I've skimmed
through old boost mailing list messages and saw some traffic last Fall
regarding a "dynany" class that seems to address that type of problem.
That is, consider the following code:
class Foo
{
public:
virtual ~Foo() {}
virtual int get() const = 0;
}; // class Foo
class Bar : public Foo
{
public:
~Bar() {}
int get() const
{
return 42;
}
}; // class Bar
int
main( int argn, char ** argv )
{
any a = Bar();
try
{
Foo * f = any_cast<Foo>(&a);
if ( ! f )
{
cerr << "bwana\n";
return -2;
}
cout << f->get() << endl;
}
catch(const boost::bad_any_cast &)
{
cerr << "bwack\n";
return -1;
}
return 0;
}
For which I get the following from g++ 3.2.2:
/home/mcoletti/include/boost_1_30_0/boost/any.hpp: In instantiation of
`boost::any::holder<Foo>':
/home/mcoletti/include/boost_1_30_0/boost/any.hpp:158: instantiated
from `ValueType* boost::any_cast(boost::any*) [with ValueType = Foo]'
foo.cc:95: instantiated from here
/home/mcoletti/include/boost_1_30_0/boost/any.hpp:102: cannot declare
field `boost::any::holder<Foo>::held' to be of type `Foo'
/home/mcoletti/include/boost_1_30_0/boost/any.hpp:102: because the
following virtual functions are abstract:
foo.cc:55: virtual int Foo::get() const
Natch, making Foo::get() non pure virtual appeases the compiler, but
now I've traded a compilation error for a run-time one since Foo and
Bar's typeid()s obviously don't match. The critical source in
<boost/any.hpp> is:
template<typename ValueType>
ValueType * any_cast(any * operand)
{
return operand && operand->type() == typeid(ValueType)
? &static_cast<any::holder<ValueType> *>(operand->content)->held
: 0;
}
Something like use of the RTTI "before" operator would yield true, and
more accurately reflects what I want.
Any work-around suggestions? Any work continuing on dynany?
Cheers!
Mark
-- Mark Coletti | He who hesitates is trampled by the mob. mailto:mcoletti_at_[hidden] | http://www.lychnobite.org/ |
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk