Boost: polymorphic_cast is used to implement down cast. If the conversion fails, an exception is thrown.
This is similar to dynamic_cast. However, if the dynamic_cast pointer fails to be converted, no exception is thrown.
The following is an example of the two:
# Ifndef base_for_cast
# Define base_for_cast
# Include <iostream>
# Include <boost/cast. HPP>
# Include <boost/scoped_ptr.hpp>
Class base1
{
Public:
Virtual void print ()
{
STD: cout <"base1: Print" <STD: Endl;
}
Virtual ~ Base1 (){}
Protected:
PRIVATE:
};
Class base2
{
Public:
Void only_base2 ()
{
STD: cout <"only base2" <STD: Endl;
}
Virtual ~ Base2 (){}
Protected:
PRIVATE:
};
Class derived: Public base1, public base2
{
Public:
Void print ()
{
STD: cout <"derived: Print" <STD: Endl;
}
Void only_here ()
{
STD: cout <"only derived 2" <STD: Endl;
}
Void only_base2 ()
{
STD: cout <"derived base2" <STD: Endl;
}
~ Derived () {STD: cout <"derived destuctor" <STD: Endl ;}
};
Void test_polymorphic_cast ()
{
Base1 * P1 = new derived;
Boost: scoped_ptr <base1> BSP (P1 );
P1-> Print ();
Try
{
Derived * Pd = boost: polymorphic_cast <derived *> (P1 );
Pd-> only_base2 ();
Pd-> only_here ();
Base2 * PBS = boost: polymorphic_cast <base2 *> (P1 );
PBS-> only_base2 ();
}
Catch (STD: bad_cast & E)
{
STD: cout <E. What () <STD: Endl;
}
}
Void polyporphic_cast_example (base1 * P)
{
Derived * D = boost: polymorphic_cast <derived *> (P );
D-> Print ();
Base2 * b2 = boost: polymorphic_cast <base2 *> (P );
B2-> only_base2 ();
}
The above code is compiled and tested through vs2008. Note that the boost library path is set.