Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Template is_fundamental ใน C++

ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ template std::is_fundamental ใน C++ STL

is_fundamental เป็น template ใน header <type_traits> ใช้ตรวจสอบว่าชนิด T เป็น fundamental data type หรือไม่

Fundamental Type คืออะไร?

Fundamental types คือ built-in types ที่คอมไพเลอร์ประกาศไว้แล้ว เช่น int, float, char, double เป็นต้น เรียกอีกอย่างว่า built-in data types

ชนิดข้อมูลที่ผู้ใช้นิยามเอง เช่น class, enum, struct, references, pointers ไม่ใช่ fundamental type

ไวยากรณ์

template <class T> is_fundamental;

พารามิเตอร์

Template รับพารามิเตอร์ชนิด T เพียงอย่างเดียว ตรวจสอบว่าเป็น fundamental type หรือไม่

ค่าที่คืน

คืนค่า Boolean: true หากเป็น fundamental data type, false หากไม่ใช่

ตัวอย่าง

Input: class final_abc; is_fundamental<final_abc>::value; Output: false
Input: is_fundamental<int>::value; Output: true
Input: is_fundamental<int*>::value; Output: false

ตัวอย่างโค้ด 1

#include <iostream>
#include <type_traits>
using namespace std;

class TP { };

int main() {
    cout << boolalpha;
    cout << "checking for is_fundamental:";
    cout << "\nTP: " << is_fundamental<TP>::value;
    cout << "\nchar :" << is_fundamental<char>::value;
    cout << "\nchar& :" << is_fundamental<char&>::value;
    cout << "\nchar* :" << is_fundamental<char*>::value;
    return 0;
}

เอาต์พุต

checking for is_fundamental:
TP: false
char : true
char& : false
char* : false

ตัวอย่างโค้ด 2

#include <iostream>
#include <type_traits>
using namespace std;

int main() {
    cout << boolalpha;
    cout << "checking for is_fundamental:";
    cout << "\nint: " << is_fundamental<int>::value;
    cout << "\ndouble :" << is_fundamental<double>::value;
    cout << "\nint& :" << is_fundamental<int&>::value;
    cout << "\nint* :" << is_fundamental<int*>::value;
    cout << "\ndouble& :" << is_fundamental<double&>::value;
    cout << "\ndouble* :" << is_fundamental<double*>::value;
    return 0;
}

เอาต์พุต

checking for is_fundamental:
int: true
double : true
int& : false
int* : false
double& : false
double* : false