4

From the following

Can I turn unsigned char into char and vice versa?

it appears that converting a basic_string<unsigned char> to a basic_string<char> (i.e. std::string) is a valid operation. But I can't figure out how to do it.

For example what functions could perform the following conversions, filling in the functionality of these hypothetical stou and utos functions?

typedef basic_string<unsigned char> u_string;
int main() {
    string s = "dog";
    u_string u = stou(s);
    string t = utos(u);
}

I've tried to use reinterpret_cast, static_cast, and a few others but my knowledge of their intended functionality is limited.

Community
  • 1
  • 1
Chris Redford
  • 16,982
  • 21
  • 89
  • 109

2 Answers2

6

Assuming you want each character in the original copied across and converted, the solution is simple

 u_string u(s.begin(), s.end());
 std:string t(u.begin(), u.end());

The formation of u is straight forward for any content of s, since conversion from signed char to unsigned char simply uses modulo arithmetic. So that will work whether char is actually signed or unsigned.

The formation of t will have undefined behaviour if char is actually signed char and any of the individual characters in u have values outside the range that a signed char can represent. This is because of overflow of a signed char. For your particular example, undefined behaviour will generally not occur.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Peter
  • 35,646
  • 4
  • 32
  • 74
  • 1
    FWIW - complete code [here](http://coliru.stacked-crooked.com/a/a36d1718cb11f715). (I was sanity-checking that the `static_cast` in Nicol's answer wasn't needed.) – Tony Delroy Jan 06 '16 at 02:26
1

It is not a legal conversion to cast a basic_string<T> into any other basic_string<U>, even if it's legal to cast T to U. This is true for pretty much every template type.

If you want to create a new string that is a copy of the original, of a different type, that's easy:

basic_string<unsigned char> str(
    static_cast<const unsigned char*>(char_string.c_str()),
    char_string.size());
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982