與 stdis sameT T 鍵入關係
Version >= C++ 11
std::is_same<T, T>
型別關係用於比較兩種型別。它將評估為布林值,如果型別相同則為 true,否則為 false。
例如
// Prints true on most x86 and x86_64 compilers.
std::cout << std::is_same<int, int32_t>::value << "\n";
// Prints false on all compilers.
std::cout << std::is_same<float, int>::value << "\n";
// Prints false on all compilers.
std::cout << std::is_same<unsigned int, int>::value << "\n";
無論 typedef 如何,std::is_same
型別關係也將起作用。在比較 int == int32_t
的第一個例子中實際證明了這一點,但這並不完全清楚。
例如
// Prints true on all compilers.
typedef int MyType
std::cout << std::is_same<int, MyType>::value << "\n";
使用 std::is_same
在不正確地使用模板化類或函式時發出警告
當與靜態斷言結合使用時,std::is_same
模板可以成為強制正確使用模板化類和函式的有用工具。
例如,僅允許來自 int
的輸入和兩個結構的選擇的功能。
#include <type_traits>
struct foo {
int member;
// Other variables
};
struct bar {
char member;
};
template<typename T>
int AddStructMember(T var1, int var2) {
// If type T != foo || T != bar then show error message.
static_assert(std::is_same<T, foo>::value ||
std::is_same<T, bar>::value,
"This function does not support the specified type.");
return var1.member + var2;
}