简体   繁体   中英

Support for const_string in std::ostream operator <<

I'm currently using the very clever package boost::const_string until http://libcxx.llvm.org/ is available pre-packaged on Ubuntu or GCC make its __versa_string (in header ext/vstring.h ) its default string implementation. libcxx's std::string aswell as __versa_string uses _small-string optimization (SSO) by default. Default support for outputting to an std::ostream is lacking however. The code

#include <iostream>
#include <boost/const_string.hpp>

const_string<char> x;
std::cout << x << endl;

does not work unless we force x into a c-string via c_str() which becomes

std::cout << x.c_str() << endl;

which compiles and works as expected. I added the following line to const_string.hpp

template <typename T>
inline std::ostream & operator << (std::ostream & os, const boost::const_string<T> & a)
{
    return os.write(a.data(), a.size());
}

This should improve performance over x.c_str() because size() is already known and does not need to be calculated by searching for NULL as in c_str() . I works for me but I am uncertain whether it works all cases. Have I missed something?

Have I missed something?

Yes, just include const_string/io.hpp . All it does however is:

return o << std::basic_string<char_type, traits_type>(s.data(), s.size());

It seems that this could have implications based on the locale and/or facets applied to the stream for strings vs just writing the straight data as you're doing.

It would be less performant, but what about creating a std::string from the const_string and using << to insert that into the stream?

No (you have not missed anything, afaik). If your aim is not to copy over content, str.data() is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM