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.