Boost.Conversion 在头文件 boost/cast.hpp 中定义了转换运算符 boost::polymorphic_cast 和 boost::polymorphic_downcast。它们旨在更精确地处理类型转换——通常使用 dynamic_cast 完成。
库由两个文件组成。分别在 boost/cast.hpp 文件中定义了 boost::polymorphic_cast 和 boost::polymorphic_downcast 这两个类型转换操作符, 在 boost/lexical_cast.hpp 文件中定义了 boost::lexical_cast。
boost::polymorphic_cast 和 boost::polymorphic_downcast 是为了使原来用 dynamic_cast 实现的类型转换更加具体。具体细节,如下例所示。
- struct father
- {
- virtual ~father() { };
- };
-
- struct mother
- {
- virtual ~mother() { };
- };
-
- struct child :
- public father,
- public mother
- {
- };
-
- void func(father *f)
- {
- child *c = dynamic_cast<child*>(f);
- }
-
- int main()
- {
- child *c = new child;
- func(c);
-
- father *f = new child;
- mother *m = dynamic_cast<mother*>(f);
- }
本例使用