How do I use boost::lexical_cast and std::boolalpha? i.e. boost::lexical_cast< bool>(“true”)

前端 未结 3 856
再見小時候
再見小時候 2020-12-30 01:25

I\'ve seen some answers to other boost::lexical_cast questions that assert the following is possible:

bool b = boost::lexical_cast< bool >         


        
3条回答
  •  旧巷少年郎
    2020-12-30 01:37

    I'm posting the answer to my own question here for others who may be looking for something like this:

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

    usage:

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

提交回复
热议问题