ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_scalar ใน C++ STL
is_scalar เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น scalar type หรือไม่
Template นี้เป็นการรวมของ is_arithmetic, is_pointer, is_enum, is_member_pointer หรือ is_same หากอย่างใดอย่างหนึ่งเป็น true ผลลัพธ์ของ is_scalar ก็จะเป็น true
Scalar Type ใน C++ คืออะไร?
Scalar type คือออบเจกต์ที่ไม่ใช่ class type และไม่ใช่ array type Scalar type เป็นชนิดที่มีฟังก์ชันการบวกในตัว (built-in addition operator) โดยไม่ต้อง overload
ไวยากรณ์
template <class T> is_scalar;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น scalar type หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น scalar type, false หากไม่ใช่
ตัวอย่าง
Input: is_scalar<int>::value; Output: true Input: is_scalar<A>::value; // A เป็นออบเจกต์ของคลาส Output: false
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
class TP { };
cout << boolalpha;
cout << "checking for is_scalar: ";
cout << "\nint(TP::*): " << is_scalar<int(TP::*)>::value;
cout << "\nint *: " << is_scalar<int*>::value;
cout << "\nbool: " << is_scalar<bool>::value;
cout << "\nint(int): " << is_scalar<int(int)>::value;
return 0;
}
เอาต์พุต
checking for is_scalar: int(TP::*): true int *: true bool: true int(int): false
ตัวอย่างโค้ด 2
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
class TP { };
enum class TP_1 { var_1, var_2, var_3, var4 };
cout << boolalpha;
cout << "checking for is_scalar: ";
cout << "\nTP : " << is_scalar<TP>::value;
cout << "\nTP_1: " << is_scalar<TP_1>::value;
cout << "\nint[10] " << is_scalar<int[10]>::value;
cout << "\nint&: " << is_scalar<int&>::value;
cout << "\nchar&: " << is_scalar<char&>::value;
return 0;
}
เอาต์พุต
checking for is_scalar: TP : false TP_1: true int[10] false int&: false char&: false