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

Template is_pod 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_pod trong C++ STL.

is_pod là template nằm trong header <type_traits>. Dùng để kiểm tra kiểu T có phải là POD (Plain Old Data) hay không.

POD (Plain Old Data) là gì?

POD là các kiểu dữ liệu cũng tồn tại trong C cũ. POD bao gồm cả kiểu scalar. Lớp POD là lớp vừa trivial (có thể khởi tạo tĩnh) vừa standard layout (cấu trúc dữ liệu đơn giản như struct, union).

Cú pháp

template <class T> is_pod;

Tham số

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

Giá trị trả về

Trả về boolean: true nếu T là POD, false nếu không.

Ví dụ

Input: class final_abc{ final_abc(); }; is_pod<final_abc>::value; Output: False
Input: is_pod<int>::value; Output: True

Ví dụ

#include <iostream> #include <type_traits> using namespace std; struct TP_1 {    int var_1; }; struct TP_2 {    int var_2;    private:    int var_3; }; struct TP_3 {    virtual void dummy(); }; int main() {    cout << boolalpha;    cout << "checking for is_pod:";    cout << "\nTP_1: " << is_pod<TP_1>::value;    cout << "\nTP_2: " << is_pod<TP_2>::value;    cout << "\nTP_3: " << is_pod<TP_3>::value;    return 0; }

Đầu ra

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

checking for is_pod: TP_1: true TP_2: false TP_3: false

Ví dụ

#include <iostream> #include <type_traits> using namespace std; class TP_1 {    int var_1; }; class TP_2 {    int var_2;    private:    int var_3; }; class TP_3 {    virtual void dummy(); }; int main() {    cout << boolalpha;    cout << "checking for is_pod:";    cout << "\nTP_1: " << is_pod<TP_1>::value;    cout << "\nTP_2: " << is_pod<TP_2>::value;    cout << "\nTP_3: " << is_pod<TP_3>::value;    return 0; }

Đầu ra

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

checking for is_pod: TP_1: true TP_2: true TP_3: false