ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_arithmetic ใน C++ STL
is_arithmetic template ช่วยตรวจสอบว่าชนิด T ที่กำหนดเป็น arithmetic type หรือไม่
Arithmetic Type คืออะไร?
Arithmetic type ประกอบด้วย 2 ประเภท:
- Integral types - จำนวนเต็ม: char, bool, int, long, short, long long, wchar_t, char16_t, char32_t
- Floating point types - จำนวนจุดลอยตัว: float, double, long double
Template is_arithmetic ตรวจสอบชนิด T ว่าเป็น arithmetic type หรือไม่ คืนค่า true หรือ false
ไวยากรณ์
template <class T> is_arithmetic;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น arithmetic type หรือไม่
ค่าที่คืน
คืนค่า bool: true หากเป็น arithmetic type, false หากไม่ใช่
ตัวอย่าง
Input: is_arithmetic<bool>::value; Output: true Input: is_arithmetic<class_a>::value; Output: false
ตัวอย่างโค้ด 1
#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 << "\nFor Bool value: " << is_arithmetic<bool>::value;
cout << "\nFor long value : " << is_arithmetic<long>::value;
cout << "\nFor 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
ตัวอย่างโค้ด 2
#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 * : false Char *: false Float *: false Double *: false