首页 > 后端开发 > C++ > 正文

以下是根据您提供的文章内容生成的英文问答类标题: Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?

Linda Hamilton
发布: 2024-10-25 22:00:28
原创
924 人浏览过

以下是根据您提供的文章内容生成的英文问答类标题:

Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?

char、signed char 和 unsigned char 之间的行为差​​异

下面的代码可以成功编译,但 char 的行为与整数类型不同。

cout << getIsTrue< isX<int8>::ikIsX  >() << endl;
cout << getIsTrue< isX<uint8>::ikIsX  >() << endl;
cout << getIsTrue< isX<char>::ikIsX  >() << endl;
登录后复制

结果是三种类型的三种实例化模式:int8、uint8 和 char。为什么会发生这种情况?

对于整数则不然: int 和 uint32 导致一种模式实例化,而signed int 导致另一种模式实例化。

原因可能是因为 C 对待 char ,有符号字符和无符号字符作为三种不同的类型。而 int 与signed int 相同。这是真的还是我错过了什么?

<code class="cpp">#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;
};


// Это  int==int32 неоднозначно
//template <>            struct isX<int  >    { typedef FalseType ikIsX; };  // Ошибка
template <>            struct isX<int32  >  { typedef FalseType ikIsX; };
template <>            struct isX<uint32 >  { typedef FalseType ikIsX; };


// Почему это не двусмысленно? 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;

}
登录后复制

我正在使用 g 4.something

以上是以下是根据您提供的文章内容生成的英文问答类标题: Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!