下面的代碼會編譯,但對於char類型而言,其行爲與int類型不同。char!=(signed char),char!=(unsigned char)
特別
cout << getIsTrue< isX<int8>::ikIsX >() << endl;
cout << getIsTrue< isX<uint8>::ikIsX >() << endl;
cout << getIsTrue< isX<char>::ikIsX >() << endl;
結果在模板3個實例爲三種類型:INT8,UINT8和炭。是什麼賦予了?
對於ints:int和uint32也是如此,它們導致相同的模板實例化,並對另一個int進行了簽名。
原因似乎是C++將char,signed char和unsigned char看作三種不同的類型。而int與signed 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;
}
我用G ++ 4.something
你還應該注意,不能保證`int8_t`將是一個`簽署char`和`uint8_t`將是一個'無符號char`。特別是在Solaris上,如果`char`被簽名,`int8_t`就是`char`。換句話說,你的代碼將無法在那裏編譯。 – 2016-10-11 15:05:57
「int和uint32導致相同的模板實例化,並且對另一個int進行了signed int」這應該肯定是int的簽名方式。 – 2018-03-07 13:24:50