与 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;
}