下面的代码编译,但具有用于char类型比用于int型不同的行为。

在特定

   cout << getIsTrue< isX<int8>::ikIsX  >() << endl;
   cout << getIsTrue< isX<uint8>::ikIsX  >() << endl;
   cout << getIsTrue< isX<char>::ikIsX  >() << endl;

结果在模板3个实例为三种类型:INT8,UINT8和炭。是什么给了?

同样是不正确的用于整数:int和UINT32其导致相同的模板实例,和INT另一个签署

的原因似乎是,C ++看到字符,符号的字符和无符号的字符作为三种不同类型。而int是相同的符号int。这是正确的还是我失去了一些东西?

#include <iostream>

using namespace std;

typedef   signed char       int8;
typedef unsigned char      uint8;
typedef   signed short      int16;
typedef unsigned short     uint16;
typedef   signed int        int32;
typedef unsigned int       uint32;
typedef   signed long long  int64;
typedef unsigned long long uint64;

struct TrueType {};
struct FalseType {};

template <typename T>
struct isX
{
   typedef typename T::ikIsX ikIsX;
};


// This  int==int32 is ambiguous
//template <>            struct isX<int  >    { typedef FalseType ikIsX; };  // Fails
template <>            struct isX<int32  >  { typedef FalseType ikIsX; };
template <>            struct isX<uint32 >  { typedef FalseType ikIsX; };


// Whay isn't this ambiguous? char==int8
template <>            struct isX<char  >  { typedef FalseType ikIsX; };
template <>            struct isX<int8  >  { typedef FalseType ikIsX; };
template <>            struct isX<uint8 >  { typedef FalseType ikIsX; };


template <typename T> bool getIsTrue();
template <>           bool getIsTrue<TrueType>() { return true; }
template <>           bool getIsTrue<FalseType>() { return false; }

int main(int, char **t )
{
   cout << sizeof(int8) << endl;  // 1
   cout << sizeof(uint8) << endl; // 1
   cout << sizeof(char) << endl;  // 1

   cout << getIsTrue< isX<int8>::ikIsX  >() << endl;
   cout << getIsTrue< isX<uint8>::ikIsX  >() << endl;
   cout << getIsTrue< isX<char>::ikIsX  >() << endl;

   cout << getIsTrue< isX<int32>::ikIsX  >() << endl;
   cout << getIsTrue< isX<uint32>::ikIsX  >() << endl;
   cout << getIsTrue< isX<int>::ikIsX  >() << endl;

}

我使用克++ 4.something

有帮助吗?

解决方案

下面是你的答案与标准:

  

3.9.1基本类型[basic.fundamental]

     

声明为字符(char)对象应足够大,以存储执行的基本字符集的任何成员。如果从这个组的字符被存储在字符对象时,该角色对象的积分值等于该字符的单个字符的文本形式的值。它是实现定义一个char对象是否能够维持负值。字符可以被显式声明unsignedsigned。的 平原charsigned char,和unsigned char三种不同类型。 :一种char,一个signed charunsigned char占据存储相同量的并具有相同的对准要求( basic.types );也就是说,它们具有相同的对象表示。对于字符类型,对象表示的所有位参加的值表示。无符号字符类型,则该值表示的所有可能的位模式代表号码。这些要求不持有其他类型。在任何特定的   实施方案中,一个普通的char对象可以采取或者作为signed charunsigned char相同的值;哪一个是实现定义的。

其他提示

有关的问题,例如这一点,我喜欢看到对于C的理由文件,这通常提供了答案,C ++的奥秘,以及,在读标准时,有时会出现我。它是这样说的吧:

  

三种类型的炭的指定:签署,平原,和无符号的。如任一符号或无符号,这取决于实现方式中,如在现有实践中一个普通的炭可表示。该类型有符号的字符被介绍给做出那些实施的char为无符号的系统可用一个字节有符号整数类型。对于对称的原因,签订的关键字可以为其他整数类型的类型名称的一部分。

理由对C

虽然大多数积分类型,如shortint默认为是signedchar不具有在C默认标牌++。

这是一个常见的错误,C ++程序员碰上,当他们使用char作为8位整数类型。

这是正确的,charunsigned charsigned char是分开的类型。或许,这将是很好,如果char只是为了要么signed charunsigned char取决于你的编译器实现的代名词,但标准说,他们是不同的类型。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top