![](/img/trans.png)
[英]How can I use boost::lexical_cast with folly::fbstring?
[英]How do I use boost::lexical_cast and std::boolalpha? i.e. boost::lexical_cast< bool >(“true”)
我已經看到其他boost::lexical_cast
問題的一些答案,這些問題斷言以下是可能的:
bool b = boost::lexical_cast< bool >("true");
這對我使用 g++ 4.4.3 boost 1.43 不起作用。 (也許它確實適用於默認設置std::boolalpha
的平台)
這是 string to bool 問題的一個很好的解決方案,但它缺少 boost::lexical_cast 提供的輸入驗證。
除了 poindexter 的答案形式之外,您還可以將這里的方法包裝在boost::lexical_cast
的專門版本中:
namespace boost {
template<>
bool lexical_cast<bool, std::string>(const std::string& arg) {
std::istringstream ss(arg);
bool b;
ss >> std::boolalpha >> b;
return b;
}
template<>
std::string lexical_cast<std::string, bool>(const bool& b) {
std::ostringstream ss;
ss << std::boolalpha << b;
return ss.str();
}
}
並使用它:
#include <iostream>
#include <boost/lexical_cast.hpp>
//... specializations
int main() {
bool b = boost::lexical_cast<bool>(std::string("true"));
std::cout << std::boolalpha << b << std::endl;
std::string txt = boost::lexical_cast< std::string >(b);
std::cout << txt << std::endl;
return 0;
}
我個人喜歡這種方法,因為它隱藏了任何特殊代碼(例如,使用LocaleBool
或to_bool(...)
)來轉換為to_bool(...)
/從to_bool(...)
值轉換。
我在這里發布了我自己的問題的答案,供其他可能正在尋找這樣的人使用:
struct LocaleBool {
bool data;
LocaleBool() {}
LocaleBool( bool data ) : data(data) {}
operator bool() const { return data; }
friend std::ostream & operator << ( std::ostream &out, LocaleBool b ) {
out << std::boolalpha << b.data;
return out;
}
friend std::istream & operator >> ( std::istream &in, LocaleBool &b ) {
in >> std::boolalpha >> b.data;
return in;
}
};
用法:
#include <boost/lexical_cast.hpp>
#include <iostream>
#include "LocaleBool.hpp"
int main() {
bool b = boost::lexical_cast< LocaleBool >("true");
std::cout << std::boolalpha << b << std::endl;
std::string txt = boost::lexical_cast< std::string >( LocaleBool( b ) );
std::cout << txt << std::endl;
return 0;
}
將您自己的模板放在用於解析的 boost 詞法轉換之上。 請注意示例中的“默認”參數以確保重載正常工作(如果您願意,可以隨意使用其他方法)。
template<typename T>
T Parse(const std::string& valStr, const T& default=T()) {
T result = boost::lexical_cast<T>(valStr);
}
然后,您可以專攻任何事物,包括布爾值:
template<>
bool Parse(const std::string& valStr, const bool& default=true) {
if(strcmp(valStr.c_str(), "true") == 0) {
return true;
}
return false;
}
顯然有很多方法可以做到這一點,您可以為真與假添加更多條件(我會確保“真”和“假”的所有變體,如“真”,加上“T”和“F”正確工作)。 您甚至可以將其擴展到數字解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.