开发者

Why same types are different?

Why this (char is signed on my implementation):

cou开发者_开发百科t << std::is_same< char,signed char>::value;

outputs false?


The three types were introduced at different times.

From the C99 Rational:

Three types of char are specified:
signed, plain, and unsigned. A plain char may be represented as either signed or unsigned depending upon the implementation, as in prior practice. The type signed char was introduced in C89 to make available a one-byte signed integer type on those systems which implement plain char as unsigned char.

They have to stay separate types in C++, to allow overloading on char to be portable.


In case you are using Visual Studio, see here: http://msdn.microsoft.com/en-us/library/cc953fe1.aspx

The C++ compiler treats variables of type char, signed char, and unsigned char as having different types. Variables of type char are promoted to int as if they are type signed char by default, unless the /J compilation option is used. In this case they are treated as type unsigned char and are promoted to int without sign extension.

[Edit] Straight from the ISO C++0x Standard, paragraph 3.9.1 (page 71, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf):

Characters can be explicitly declared unsigned or signed. Plain char, signed char, and unsigned char are three distinct types.


char, signed char and unsigned char are three distinct types, even if char is interpreted in the same way as signed char is interpreted by your compiler.

§3.9.1/1 from the C++ Standard says

Plain char, signed char, and unsigned char are three distinct types.

In other words, dont think of char as short-form of signed char, because it's not.

Just to emphasize how types could be different despite their bit interpretation being same, consider these two structs:

struct A
{
   int i;
};

struct B
{
   int i;
};

Are they same? Of course not. Exactly in the same way, char and signed char are distinct types.

Try this:

 cout << std::is_same<A,B>::value;


C++ Standard (quoting Working Draft №3225, 2010-11-27)

3.9.1 Fundamental types

Plain char, signed char, and unsigned char are three distinct types.


That depends on the implementation, but if I remember correctly I read somewhere that these two should be different, in order to differentiate c type strings from a 8-bit signed number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜