Support for const_string in std::ostream operator <<
Asked Answered
E

3

10

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?

Exterior answered 20/4, 2011 at 13:30 Comment(2)
That depends on which behaviour you want for non-printable characters (especially \0), I guess. I think (!) the default behaviour for normal strings is to truncate after null chars. Your implementation probably won’t do that. By the way, +1 for making me aware of boost::const_string.Refit
I think this is a kind of trade-off. As far as I see, your code doesn't reflect manipulator settings like std::setw. If you don't use those manipulators for const_string, I think your code has its own use.Jacintha
S
3

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());
Snippy answered 21/4, 2011 at 10:20 Comment(2)
Is that as fast as my alternative?Servomotor
@Nordlöw: Quite likely, e.g. it construct a temporary basic_string - but then again you don't have to deal with locales et al. Anyway, i'd measure it if it really matters in your application.Snippy
I
2

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?

Interactive answered 20/4, 2011 at 14:38 Comment(1)
Thanks for your comments. How do I support locale settings then?Servomotor
N
1

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

Nicolnicola answered 20/4, 2011 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.