C++ 中的 is_pointer 模板


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

is_pointer 是一個模板,位於 <type_traits> 標頭檔案中。此模板用於檢查給定型別 T 是否為指標型別。

什麼是指標?

指標是非靜態型別,它儲存了另一種型別的地址,換句話說,它指向了記憶體池中的某個記憶體位置。在星號 (*) 的幫助下,我們定義一個指標,當我們想要引用指標所指向的特定記憶體時,我們也使用星號 (*)。

這種型別可以初始化為 null,且可以根據需要稍後更改此型別。

語法

template <class T> is_pod;

引數

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

返回值

它返回一個布林值,如果給定型別是一個指標變數,則為真,如果給定型別不是指標,則為假。

示例

Input: is_pointer<int>::value;
Output: False

Input: is_pointer<int*>::value;
Output: True

示例

即時演示

#include <iostream>
#include <type_traits>
using namespace std;
class TP{
};
int main() {
   cout << boolalpha;
   cout << "checking for is_pointer:";
   cout << "\nTP: " << is_pointer<TP>::value;
   cout << "\nTP*: " << is_pointer<TP*>::value;
   cout << "\nTP&: " << is_pointer<TP&>::value;
   cout << "\nNull Pointer: "<< is_pointer<nullptr_t>::value;
   return 0;
}

輸出

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

checking for is_pointer:
TP: false
TP*: true
TP&: false
Null Pointer: false

示例

即時演示

#include <iostream>
#include <type_traits>
using namespace std;
int main() {
   cout << boolalpha;
   cout << "checking for is_pointer:";
   cout << "\nint: " << is_pointer<int>::value;
   cout << "\nint*: " << is_pointer<int*>::value;
   cout << "\nint **: " << is_pointer<int **>::value;
   cout << "\nint ***: "<< is_pointer<int ***>::value;
   return 0;
}

輸出

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

checking for is_pointer:
int: false
int*: true
Int **: true
Int ***: true

更新於:2020 年 3 月 23 日

339 次瀏覽

啟動您的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.