C++ containers and byte strings

C++ allows you to construct a std::string from a pointer to const char, like this:

std::string s("Hello, world!");

But this particular method has a limitation: even though std::strings can contain the null character, the constructor will only read up to the first null in the byte string.

std::string s("Hello\0, world!");

In the code above, s will contain only "Hello".

To get round that, we can use a function template:

#include <string>

template<typename T, size_t N>
std::string
fromByteString(T(&buf)[N])
{
    return std::string(buf, buf + N - 1);
}

std::string s(fromByteString("Hello\0, world!"));

A good compiler should be able to elide the std::string copies during construction and inline the template instantiations, so this is an efficient way to construct strings containing any kind of data.

Because the function template just retrieves a begin and end iterator (pointers can be iterators) for the buffer, it can easily be modified to construct any sequence container such as list, deque, or vector.