Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Template is_fundamental trong C++


Trong bài viết này, ta sẽ thảo luận về hoạt động, cú pháp và ví dụ của template std::is_fundamental trong C++ STL.

is_fundamental là template nằm trong header <type_traits>. Dùng để kiểm tra kiểu T có phải là kiểu dữ liệu cơ bản (fundamental) hay không.

Kiểu cơ bản (Fundamental type) là gì?

Kiểu cơ bản là các kiểu built-in đã được khai báo sẵn trong trình biên dịch. Ví dụ: int, float, char, double, v.v. Còn gọi là kiểu dữ liệu nội tại.

Tất cả kiểu do người dùng định nghĩa như: class, enum, struct, reference, con trỏ, không thuộc kiểu cơ bản.

Cú pháp

template <class T> is_fundamental;

Tham số

Template chỉ có tham số kiểu T, kiểm tra T có phải kiểu cơ bản không.

Giá trị trả về

Trả về boolean: true nếu T là kiểu cơ bản, false nếu không.

Ví dụ

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

Ví dụ

#include <iostream> #include <type_traits> using namespace std; class TP {    //TP Body }; 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; }

Đầu ra

Nếu chạy mã trên sẽ cho kết quả:

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

Ví dụ

#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; }

Đầu ra

Nếu chạy mã trên sẽ cho kết quả:

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