ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_const ใน C++ STL
is_const template ใช้ตรวจสอบว่าชนิดที่กำหนดเป็น const-qualified type หรือไม่
Const-qualified Type คืออะไร?
ชนิดที่เป็น const-qualified หมายถึงค่าของชนิดนั้นเป็นค่าคงที่ (constant) ไม่สามารถเปลี่ยนแปลงได้ตลอดโปรแกรม
ไวยากรณ์
template <class T> is_const;
พารามิเตอร์
Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น const-qualifier หรือไม่
ค่าที่คืน
คืนค่า Boolean: true หากเป็น const-qualifier, false หากไม่ใช่
ตัวอย่าง
Input: is_const<const int>::value; Output: true Input: is_const<int>::value; Output: false
ตัวอย่างโค้ด 1
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_const template: ";
cout << "\nInt : " << is_const<int>::value;
cout << "\nConst int : " << is_const<const int>::value;
cout << "\nConst int& : " << is_const<const int&>::value;
return 0;
}
เอาต์พุต
checking for is_const template: Int : false Const int : true Const int& : false
ตัวอย่างโค้ด 2
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_const template: ";
cout << "\nFloat : " << is_const<float>::value;
cout << "\nChar : " << is_const<char>::value;
cout << "\nFloat *: " << is_const<float*>::value;
cout << "\nChar *: " << is_const<char*>::value;
cout << "\nConst int* : " << is_const<const int*>::value;
cout << "\nint* const : " << is_const<int* const>::value;
return 0;
}
เอาต์พุต
checking for is_const template: Float : false Char: false Float *: false Char *: false Const int* : false int* const: true
คำอธิบาย
const int*- pointer ไปยัง const int (ข้อมูลเป็น const) -> is_const = falseint* const- const pointer ไปยัง int (pointer เป็น const) -> is_const = true