ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่าง std::is_reference template ใน C++ STL
is_reference เป็นเทมเพลตที่อยู่ภายใต้ไฟล์ส่วนหัว
เทมเพลตนี้เป็นการรวมกันของ is_rvalue และ is_lvalue และตรวจสอบว่าสิ่งใดสิ่งหนึ่งเป็นจริง ผลลัพธ์ของ is_reference จะเป็นจริงด้วย
การอ้างอิงใน C++ คืออะไร
การอ้างอิงคือนามแฝงหรือชื่ออื่นของตัวแปรที่มีอยู่แล้ว การอ้างอิงแตกต่างจากตัวชี้ -
- เนื่องจากเราไม่สามารถตั้งค่าการอ้างอิงเป็น null ได้ แต่ตัวชี้สามารถเป็นตัวชี้ค่า null ได้
- เมื่อเริ่มต้นการอ้างอิงไปยังวัตถุแล้ว จะไม่สามารถเปลี่ยนแปลงได้ สามารถชี้ตัวชี้ไปที่วัตถุอื่นได้ตลอดเวลา
- เมื่อสร้างการอ้างอิงจะต้องเริ่มต้น โดยที่ตัวชี้สามารถเริ่มต้นได้ภายหลังการสร้าง
การอ้างอิงสามารถประกาศได้โดยใช้สัญลักษณ์ ampersand(&) นำหน้าตัวแปรที่เราต้องการอ้างอิง
ไวยากรณ์
template <class T> is_reference;
พารามิเตอร์
เทมเพลตมีได้เฉพาะพารามิเตอร์ประเภท T และตรวจสอบว่าประเภทที่กำหนดเป็นประเภทอ้างอิงหรือไม่
คืนค่า
ส่งคืนค่าบูลีนเป็นค่าจริงหากประเภทที่กำหนดเป็นประเภทอ้างอิงและเป็นเท็จหากประเภทที่ระบุไม่ใช่ประเภทอ้างอิง
ตัวอย่าง
Input: is_reference<int>::value; Output: False Input: is_reference<int&>::value; Output: True
ตัวอย่าง
#include <iostream>
#include <type_traits>
using namespace std;
class TP {
};
int main() {
cout << boolalpha;
cout << "Checking for is_reference: ";
cout << "\n class TP : "<<is_reference<TP>::value;
cout << "\n class TP&: "<<is_polymorphic<TP&>::value;
cout << "\n class TP&&: "<<is_polymorphic<TP&&>::value;
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Checking for is_reference: class TP : false class TP&: false class TP&&: false
ตัวอย่าง
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "Checking for is_reference: ";
cout << "\n int: "<<is_reference<int>::value;
cout << "\n int&: "<< is_reference <int&>::value;
cout << "\n int&&: "<< is_reference <int&&>::value;
// char
cout << "\n char: "<<is_reference<char>::value;
cout << "\n char&: "<< is_reference <char&>::value;
cout << "\n char&&: "<< is_reference <char&&>::value;
//float
cout << "\n float: "<<is_reference<float>::value;
cout << "\n float&: "<< is_reference <float&>::value;
cout << "\n float&&: "<< is_reference <float&&>::value;
//double
cout << "\n double: "<<is_reference<double>::value;
cout << "\n double&: "<< is_reference <double&>::value;
cout << "\n double&&: "<< is_reference <double&&>::value;
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Checking for is_reference: int: false int&: true int&&: true char: false char&: true char&&: true float: false float&: true float&&: true double: false double&: true double&&: true