C++ 中的 is_signed 模板


在本文中,我们将讨论 C++ STL 中 std::is_signed 模板的原理、语法和示例。

is_ signed 是一个模板,包含在 <type_traits> 头文件中。此模板用于检查给定的类型 T 是否是有符号类型。

什么是带符号类型?

这些是基本算术类型,其中包含符号值。所有算术数据类型都带有符号或不带符号。

例如,我们希望以负值显示值,我们会使用带符号类型。

例如:-1 是带符号 int,-1.009 是带符号浮点数。

默认情况下,所有类型都带有符号,使它们不带符号,我们必须在数据类型前加上 unsigned。

语法

template <class T> is_signed;

参数

此模板只能有一个类型为 T 的参数,并检查 T 是否是有符号类型。

返回值

它返回一个布尔值,如果给定的类型是有符号类型,则返回 true,如果给定的类型不是有符号类型,则返回 false。

示例

Input: is_signed<int>::value;
Output: True

Input: is_signed<unsigned int>::value;
Output: False

示例

 实时演示

#include <iostream>
#include <type_traits>
using namespace std;
class TP {
};
enum TP_1 : int {};
enum class TP_2 : int {};
int main() {
   cout << boolalpha;
   cout << "checking for is_signed:";
   cout << "\nint:" << is_signed<int>::value;
   cout << "\nTP:" << is_signed<TP>::value;
   cout << "\nTP_1:" << is_signed<TP_1>::value;
   cout << "\nTP_2:" << is_signed<TP_2>::value;
   return 0;
}

输出

如果我们运行上面的代码,它将生成以下输出 −

checking for is_signed:
Int: true
TP: false
TP_1: false
TP_2: false

示例

 实时演示

#include <iostream>
#include <type_traits>
using namespace std;
int main() {
   cout << boolalpha;
   cout << "checking for is_signed:";
   cout << "\nfloat:" << is_signed<float>::value;
   cout << "\nSigned int:" << is_signed<signed int>::value;
   cout << "\nUnsigned int:" << is_signed<unsigned int>::value;
   cout << "\ndouble:" << is_signed<double>::value;
   return 0;
}

输出

如果我们运行上面的代码,它将生成以下输出 −

checking for is_signed:
Float: true
Signed int: true
Unsigned int: false
Double: true

更新于: 2020 年 3 月 23 日

161 次浏览

启动你的 职业生涯

完成课程并获得认证

开始吧
广告
© . All rights reserved.