C++ 中的 is_arithmetic 模板


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

is_arithmetic 模板有助于检查给定类 T 是否为算术类型。

什么是算术类型?

算术类型包括两种类型,即

  • 整数类型 - 在此我们定义整数。以下是有类型的整数类型 -

    • char
    • bool
    • int
    • long
    • short
    • long long
    • wchar_t
    • char16_t
    • char32_t
  • 浮点类型 - 这些可以容纳分数部分。以下是浮点类型 -

    • Float
    • Double
    • Long double

因此,template is_arithmatic 检查定义的类型 T 是否为算术类型,并相应地返回 true 或 false。

语法

template <class T> is_arithmetic;

参数

模板只能有一个参数,类型为 T,并且检查参数是否为算术类型。

返回值

此函数返回一个布尔类型的值,它可以是 true 或 false。如果给定的类型是算术类型,则返回 true;如果类型不是算术类型,则返回 false。

示例

Input: is_arithmetic<bool>::value;
Output: True

Input: is_arithmetic<class_a>::value;
Output: false

示例

 实时演示

#include <iostream>
#include <type_traits>
using namespace std;
class TP {
};
int main() {
   cout << boolalpha;
   cout << "checking for is_arithmetic template:";
   cout << "\nTP class : "<< is_arithmetic<TP>::value;
   cout << "\n For Bool value: "<< is_arithmetic<bool>::value;
   cout << "\n For long value : "<< is_arithmetic<long>::value;
   cout << "\n For Short value : "<< is_arithmetic<short>::value;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 -

checking for is_arithmetic template:
TP class : false
For Bool value: true
For long value : true
For Short value : true

示例

 实时演示

#include <iostream>
#include <type_traits>
using namespace std;
int main() {
   cout << boolalpha;
   cout << "checking for is_arithmetic template:";
   cout << "\nInt : "<< is_arithmetic<int>::value;
   cout << "\nchar : "<< is_arithmetic<char>::value;
   cout << "\nFloat : "<< is_arithmetic<float>::value;
   cout << "\nDouble : "<< is_arithmetic<double>::value;
   cout << "\nInt *: "<< is_arithmetic<int*>::value;
   cout << "\nchar *: "<< is_arithmetic<char*>::value;
   cout << "\nFloat *: "<< is_arithmetic<float*>::value;
   cout << "\nDouble *: "<< is_arithmetic<double*>::value;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 -

checking for is_arithmetic template:
Int : true
Char : true
Float : true
Double : true
Int * : float
Char *: float
Float *: float
Double *: float

更新于:2020 年 3 月 23 日

200 次浏览

启动你的 职业

完成课程,获得认证

开始学习
广告
© . All rights reserved.