【C++】Boost库LexicalCast模块介绍与使用

Boost库LexicalCast模块

介绍

lexical_cast库进行”字面值“之间的通用转换

头文件

#include<boost/lexical_cast.hpp>

使用

基础API

  • lexical_cast

boost::lexical_cast可以在各种基本类型中转换

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
 
    string s1;
    string s2 = "888";
    int val = 123;     
    s1 = boost::lexical_cast<string>(1.532e5);
    cout << s1 << endl;
    s1 = boost::lexical_cast<string>(1234);
    cout << s1 << endl;
    s1 = boost::lexical_cast<string>(5.265);
    cout << s1 << endl;
    val = boost::lexical_cast<int>(s2);
    cout << val << endl;
}

lexcial_cast的内部使用了标准的流操作,因此它对转换对象有如下要求:

  • Source是可流输出的(OutputStreamable),即定义了一个操作符<<
  • Target是可流输入的(InputStreamable),即义了一个操作符>>
  • Target是可复制的
  • Target是可默认构造的,这意味着可以默认初始化该类型的对象
  • bad_lexical_cast

如果转换失败,则会抛出从 std::bad_cast 派生的 boost::bad_lexical_cast 类型的异常。

    try
    {
        cout << lexical_cast<int>("0x100");
        cout << lexical_cast<double>("HelloWorld");
        cout << lexical_cast<long>("1000L");
        cout << lexical_cast<bool>("false") << endl;
    }
    catch (bad_lexical_cast& e)
    {
        cout << "error:" << e.what() << endl;
    }
  • try_lexical_convert

lexical_cast在名字空间boost::conversion提供try_lexical_convert()函数,可以避免抛出异常,它以bool返回值表示是否转换成功

    float f;
    for (auto str : {"abc", "1.2"}) {
        if (try_lexical_convert<float>(str, f)) {
            cout << "Succes"" << str << "\" to " << f << endl;
        } else {
            cout << "Fail"" << str << "\" to float" << endl;
        }
    }

自定义类型转换

如果我们想要将lexical_cast应用于自定义的类,需要实现流操作符operator

  • 自定义类转字符串
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
 
using namespace std;
 
class Point {
 public:
  Point(float x, float y) : x_(x), y_(y) {}
  friend ostream &operator<<(ostream &output, const Point &p) {
    output << "(" << p.x_ << ", " << p.y_ << ")";
    return output;
  }
 
 private:
  const float x_;
  const float y_;
};
 
int main() {
  using boost::bad_lexical_cast;
  using boost::lexical_cast;
 
  const auto s = lexical_cast<string>(Point(1.1f, 2.2f));
  cout << s << endl;
}
  • 字符串转自定义类
class Point {
 public:
  friend istream &operator>>(istream &input, Point &p) {
    input >> p.x_;
    return input;
  }
 
  friend ostream &operator<<(ostream &output, const Point &p) {
    output << "Point(" << p.x_ << ")";
    return output;
  }
 
  Point() { x_ =0; }
  Point(const Point &pt) {
    x_ = pt.x_;
  }
 
 private:
  float x_;
};
 
int main() {
  using boost::bad_lexical_cast;
  using boost::lexical_cast;
 
  const auto p = lexical_cast<Point>(string("3.3"));
  cout << p << endl;
}

参考资料1
参考资料2

  • 18
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值