2010-12-15 94 views
17

我见过一些答案到断言以下的其他boost::lexical_cast的问题是可能的:如何使用boost :: lexical_cast和std :: boolalpha?即升压:: lexical_cast的< bool >(“真”)

bool b = boost::lexical_cast<bool>("true"); 

这不适合我使用g ++ 4.4.3升压工作1.43。 (也许这是真的,它在默认设置std :: boolalpha的平台上工作)

This是一个不错的解决方案,以字符串来布尔问题,但它缺乏boost :: lexical_cast提供的输入验证。

+4

关于发布自己的问题答案的意见是混合的,但至少应将答案发布为答案。 – robert 2010-12-15 16:16:54

+3

请发表您的答案**作为答案**。 – 2010-12-15 16:17:19

+0

编辑! (出于某种原因,我没有通过电子邮件发送您的评论。) – poindexter 2010-12-17 20:24:36

回答

15

我张贴的答案,在这里我自己的问题为别人谁可能是在寻找这样的事情:

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

顺便说一句,在运营商>>或运营商<<中收到的数据流上使用'std :: boolalpha'是否是一种很好的风格?约定是否将该流设置为同一状态? – Kos 2010-12-17 20:32:31

+1

糟糕!为了保持理智,你可以在iostream上使用boost :: ios_flags_saver。 – poindexter 2011-03-24 14:49:04

+0

其实,我越想越想。如果您希望LocaleBool的提取/插入操作符在boost :: lexical_cast之外使用,则只需要尊重流的状态。所以在大多数情况下它应该是理智的,注意你不应该将它与用于实际I/O的iostream混合使用。 – poindexter 2011-03-24 14:55:03

10

除了问答形式波因德克斯特您可以将here中的方法包装为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; 
} 

我个人很喜欢这种方法,因为它隐藏任何特殊代码(例如使用来自链接的LocaleBoolto_bool(...))转换为/从bools。

0

把你自己的模板放在提升词法转换顶层进行解析。请注意示例中的“default”参数,以确保超载正常工作(如果需要,可随意使用其他方式)。

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

显然有许多方法可以做到这一点,你可以真正VS假添加更多的条件(我想确保“TRUE”和“FALSE”的所有变体如“真”,再加上“T”和“F”)。你甚至可以将它扩展到数字解析。

相关问题