c++c++11charsignedtype-traits

Why is char distinct from signed char and unsigned char?


Consider the following code:

#include <iostream>
#include <type_traits>
 
int main()
{
    std::cout << "std::is_same<int, int>::value = " << std::is_same<int, int>::value << std::endl;
    std::cout << "std::is_same<int, signed int>::value = "<<std::is_same<int, signed int>::value << std::endl;
    std::cout << "std::is_same<int, unsigned int>::value = " << std::is_same<int, unsigned int>::value << std::endl;

    std::cout << "----" << std::endl;

    std::cout << "std::is_same<char, char>::value = " << std::is_same<char, char>::value << std::endl;
    std::cout << "std::is_same<char, signed char>::value = " << std::is_same<char, signed char>::value << std::endl;
    std::cout << "std::is_same<char, unsigned char>::value = " << std::is_same<char, unsigned char>::value << std::endl;
}

The result is :

std::is_same<int, int>::value = 1
std::is_same<int, signed int>::value = 1
std::is_same<int, unsigned int>::value = 0
----
std::is_same<char, char>::value = 1
std::is_same<char, signed char>::value = 0
std::is_same<char, unsigned char>::value = 0

Which means that int and signed int are considered as the same type, but not char and signed char. Why is that ?

And if I can transform a char into signed char using make_signed, how to do the opposite (transform a signed char to a char) ?


Solution

  • It's by design, C++ standard says char, signed char and unsigned char are different types. I think you can use static cast for transformation.