boost::polymorphic_cast用来实现down cast。如果转换不成功,则抛出一个异常。
这和dynamic_cast很类似。但是dynamic_cast转换指针失败的时候,不抛异常。
下面是二者使用的例子:
#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* pb2 = boost::polymorphic_cast<base2*>(p1);
pb2->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();
}
以上代码通过vs2008编译和测试,请注意设置好boost库的路径。