ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_signed ใน C++ STL
is_signed เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น signed type หรือไม่
Signed Type คืออะไร?
เป็น arithmetic types พื้นฐานที่มีค่าลบได้ ทุก arithmetic data types เป็น signed หรือ unsigned
ใช้ signed เมื่อต้องการแสดงค่าลบ เช่น -1 เป็น signed int, -1.009 เป็น signed float
โดยค่าเริ่มต้นทุกชนิดเป็น signed ต้อง prefix unsigned เพื่อทำให้เป็น unsigned
ไวยากรณ์
template <class T> is_signed;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น signed type หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น signed type, false หากไม่ใช่
ตัวอย่าง
Input: is_signed<int>::value; Output: true Input: is_signed<unsigned int>::value; Output: false
ตัวอย่างโค้ด 1
#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
ตัวอย่างโค้ด 2
#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