C++ std::is_pointer 完整用法
1. 头文件
必须引入:
cpp
运行
#include <type_traits> #include <iostream>2. 核心语法
老式写法(C++11)
cpp
运行
std::is_pointer<T>::value简化写法(C++17 推荐)
cpp
运行
std::is_pointer_v<T>返回bool:true是指针类型,false不是。
3. 判断类型是不是指针
cpp
运行
#include <type_traits> #include <iostream> int main() { std::cout << std::boolalpha; // 普通类型 std::cout << std::is_pointer_v<int> << '\n'; // false std::cout << std::is_pointer_v<double> << '\n'; // false // 一级指针 std::cout << std::is_pointer_v<int*> << '\n'; // true std::cout << std::is_pointer_v<double*> << '\n'; // true // 二级指针 也是指针 std::cout << std::is_pointer_v<int**> << '\n'; // true // 引用不是指针 std::cout << std::is_pointer_v<int&> << '\n'; // false // 数组不是指针 std::cout << std::is_pointer_v<int[5]> << '\n'; // false return 0; }4. 判断变量是不是指针
用decltype(变量)取变量类型,再给is_pointer
cpp
运行
int main() { int a = 10; int* p = &a; int& r = a; std::cout << std::boolalpha; std::cout << std::is_pointer_v<decltype(a)> << '\n'; // false std::cout << std::is_pointer_v<decltype(p)> << '\n'; // true std::cout << std::is_pointer_v<decltype(r)> << '\n'; // false }5. 模板中做类型分支(编译期判断)
cpp
运行
template <typename T> void checkType() { if constexpr (std::is_pointer_v<T>) { std::cout << "这是指针类型\n"; } else { std::cout << "不是指针类型\n"; } } // 调用 checkType<int>(); checkType<int*>(); checkType<int**>();6. 关键注意点
std::is_pointer只识别原生指针T*- 智能指针
std::shared_ptr/std::unique_ptr判断为 false
- 智能指针
- 引用
T&不是指针,判 false - 数组
T[N]不是指针,判 false - 是编译期判断,无运行时开销
7. 一句话记忆
- 类型直接填:
std::is_pointer_v<int*> - 变量用
decltype包一层:std::is_pointer_v<decltype(var)> - C++17 用
_v后缀更简洁。
