当前位置: 代码迷 >> 综合 >> boost学习-3.conversion,多态类型之间的安全转型,与数据类型转换
  详细解决方案

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

热度:91   发布时间:2024-01-20 00:37:36.0

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

 

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;
}

 

 

 

  相关解决方案