C++ 中的 is_fundamental 模板


在本文中,我們將討論 C++ STL 的 std::is_fundamental 模板的工作方式、語法和示例。

is_fundamental 是一個模板,位於 <type_traits> 標頭檔案中。此模板用於檢查給定的型別 T 是否為基礎資料型別。

什麼是基礎型別?

基礎型別是在編譯器本身中已宣告的內建型別。例如 int、float、char、double 等。這些型別也稱為內建資料型別。

所有使用者定義的資料型別(如類、列舉、結構、引用或指標)都不是基礎型別的一部分。

語法

template <class T> is_fundamental;

引數

該模板只能有一個型別為 T 的引數,並檢查給定的型別是否為最終類型別。

返回值

它返回一個布林值,如果給定的型別是基礎資料型別,則為真;如果給定的型別不是基礎資料型別,則為假。

示例

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

示例

 演示

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

輸出

如果我們執行以上程式碼,它將生成以下輸出 -

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

示例

 演示

#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

更新於:2020 年 3 月 23 日

153 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告