Search code examples
boostsignlexical-cast

boost::lexical_cast with positive sign


How can I make boost::lexical_cast include a positive sign when converting to std::string?

I intend to do the same as: snprintf( someArray, someSize, "My string which needs sign %+d", someDigit );. Here, someDigit would be put in the string as +someDigit if it were positive, or -someDigit if it were negative. See: http://www.cplusplus.com/reference/clibrary/cstdio/snprintf/


Solution

  • How can I make boost::lexical_cast include a positive sign when converting to std::string?

    There is no way to control the formatting of built-in types when using boost::lexical_cast<>.

    boost::lexical_cast<> uses streams to do the formatting. Hence, one can create a new class and overload operator<< for it and boost::lexical_cast<> will use that overloaded operator to format values of the class:

    #include <boost/lexical_cast.hpp>
    #include <iomanip>
    #include <iostream>
    
    template<class T> struct ShowSign { T value; };
    
    template<class T>
    std::ostream& operator<<(std::ostream& s, ShowSign<T> wrapper) {
        return s << std::showpos << wrapper.value;
    }
    
    template<class T>
    inline ShowSign<T> show_sign(T value) {
        ShowSign<T> wrapper = { value };
        return wrapper;
    }
    
    int main() {
        std::string a = boost::lexical_cast<std::string>(show_sign(1));
        std::cout << a << '\n';
    }