首頁 > 後端開發 > 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學習者快速成長!