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

poindexter picture poindexter · Dec 15, 2010 · Viewed 21.5k times · Source

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

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

This doesn't work for me with g++ 4.4.3 boost 1.43. (Maybe it's true that it works on a platform where std::boolalpha is set by default)

This is a nice solution to the string to bool problem but it lacks input validation that boost::lexical_cast provides.

Answer

poindexter picture poindexter · Dec 17, 2010

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