boost中的类型转换操作符
零、小序
标准C++中提供了四种类型转换运算符dynamic_cast、static_cast、const_cast和reinterpret_cast,大大方便了程序员对类型转换的使用,boost是C++程序员经常使用的第三方库,它同样提供了一些很好用的类型转换操作,甚至有些使用起来比C++标准库更方便。
有关C++标准库提供的类型转换运算符可以看这篇文章的详细解读:https://blog.csdn.net/toby54king/article/details/105310923
一、动态转换操作符
1、polymorphic_cast和polymorphic_downcast
C++标准库提供的动态转换操作符dynamic_cast既可以向上转换又可以向下转换,而boost库提供的类型转换运算符把这两种情况拆分开了。polymorphic_cast提供向上转换的操作,polymorphic_downcast提供向下转换的操作。
boost::polymorphic_cast内部使用了dynamic_cast,可以实现交叉转换的类型转换操作符,boost::polymorphic_cast能够在错误的时候抛出 std::bad_cast 类型的异常。
boost::polymorphic_downcast类型转换操作符只能用于向下转换,它的内部使用 static_cast 实现类型转换。 所以polymorphic_downcast并不动态检查类型转换是否合法,需要程序员自己确保转换安全。
2、代码示例
// BoostCastType.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <boost/cast.hpp>
using namespace std;
using namespace boost;
class Father
{
public:
Father() {
cout << "Father!" << endl; };
~Father() {
};
virtual void MyPrintf()
{
cout << "this is a Father class!" << endl;
}
private:
};
class Mother
{
public:
Mother() {
cout << "Mother!" << endl; };
~Mother() {
};
virtual void MyPrintf()
{
cout << "this is a Mother class!" << endl;
}
private:
};
class Child:public Father,