Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
Nordlöw Avatar asked Apr 20 '11 13:04

Nordlöw


Video Answer


3 Answers

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());
like image 96
Georg Fritzsche Avatar answered Sep 22 '22 01:09

Georg Fritzsche


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?

like image 24
Mark B Avatar answered Sep 21 '22 01:09

Mark B


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

like image 38
Gabriel Avatar answered Sep 22 '22 01:09

Gabriel