Search code examples
c++stringcharunsigned

Can I get a char* out of either signed char* or unsigned char*?


I have to deal with char arrays which might be unsigned (because they come from a SCSI data block). I wanted to handle them with this function:

template <typename CharT, size_t Len>
std::string strFromArray(CharT (&src) [Len])
{     
    return std::string((typename boost::make_signed<CharT>::type *) src, Len);
}

The error is in the std::string constructor call, it cannot take signed char/unsigned char but will only take char.

I could of course replace the cast with (char *) src, but then I would lose all compiler errors if I pass in a non-char type.

How can I write this so that it constructs strings out of all "charry" types?


Solution

  • Just place an static assert into your function and modify it slightly:

    #include <string>
    
    template <typename CharT, std::size_t Len>
    std::string strFromArray(CharT (&src) [Len])
    {
        // Anythig which looks like a char is considered a char.
        static_assert(sizeof(CharT) == sizeof(char), "Invalid Character Type");
        std::size_t n = Len;
        // Do not use a terminating zero (might be wrong if the source is no char 
        // literal, but an array of binary data.
        if( ! src[n-1])
            --n;
        return std::string(src, src + n);
    }
    
    int main()
    {
        char c[3] = {};
        signed char sc[3] = {};
        unsigned char uc[3] = {};
        wchar_t wc[3] = {};
        strFromArray(c);
        strFromArray(sc);
        strFromArray(uc);
        // error: static assertion failed: Invalid Character Type
        // strFromArray(wc);
    }