boost学习-3.conversion,多态类型之间的安全转型,与数据类型转换

来源:互联网 发布:365桌面提醒器源码 编辑:程序博客网 时间:2024/05/16 12:29

这个库比较简单,看例子就明白啦

 

1.多态类型之间的安全转型

 

polymorphic_cast 和 polymorphic_downcast 

 

 

namespace boost {

template <class Derived, class Base>
inline Derived polymorphic_cast(Base* x);
// 抛出: std::bad_cast 如果 ( dynamic_cast<Derived>(x) == 0 )
// 返回: dynamic_cast<Derived>(x)

template <class Derived, class Base>
inline Derived polymorphic_downcast(Base* x);
// 效果: assert( dynamic_cast<Derived>(x) == x );
// 返回: static_cast<Derived>(x)

}

#include <boost/cast.hpp>
...
class Fruit { public: virtual ~Fruit(){}; ... };
class Banana : public Fruit { ... };
...
void f( Fruit * fruit ) {
// ... 我们确信 fruit 是一个 Banana
Banana * banana = boost::polymorphic_downcast<Banana*>(fruit);
...

2.数据类型转换

lexical_cast<>

 

#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace boost;
using namespace std;
int main()
{
    int i = lexical_cast<int>("123444");
    cout<<"i="<<i<<endl;

    string s = lexical_cast<string>(i);
    cout<<"string s = "<<s<<endl;

    double d1 = 1.345678900;
    s = lexical_cast<string>(d1);
    cout<<"string s = "<<s<<endl;

    return 0;
}

 

 

 

原创粉丝点击