c++之std::remove_pointer

该函数是一个模板函数,移除T类型的指针类型,如果T类型不是指针,那么去除的类型与T类型相同。

语法:

#include <type_traits>

template <class T>
using remove_pointer_t = typename std::remove_pointer<T>::type;

 

#include <type_traits>
#include <iostream>

int main() {
// Example 1: Removing pointer qualifiers
static_assert(std::is_same_v<std::remove_pointer_t<int*>, int>, "int* becomes int");
static_assert(std::is_same_v<std::remove_pointer_t<int**>, int*>, "int** becomes int*");
static_assert(std::is_same_v<std::remove_pointer_t<int>, int>, "int remains int");

// Example 2: Using with const and volatile pointers
static_assert(std::is_same_v<std::remove_pointer_t<const int*>, int>, "const int* becomes int");
static_assert(std::is_same_v<std::remove_pointer_t<int* const>, int>, "int* const becomes int");

// Example 3: Practical application
int value = 42;
int* ptr = &value;
std::remove_pointer_t<int*> dereferenced_value = *ptr; // deduces to int
std::cout << "Dereferenced value: " << dereferenced_value << std::endl;

return 0;
}

 

实际应用:

模板编程:它通常用于泛型编程,用于推断指针的基本类型并对其进行操作。

智能指针:使用 std::unique_ptr 或 std::shared_ptr 时,std::remove_pointer_t 可以帮助确定智能指针管理的基础类型。

自定义删除器:在使用自定义删除器的场景中,std::remove_pointer_t 确保为资源管理推导出正确的类型。

#include <memory>
#include <type_traits>
#include <iostream>

void custom_deleter(int* ptr) {
std::cout << "Deleting pointer: " << ptr << std::endl;
delete ptr;
}

int main() {
std::unique_ptr<std::remove_pointer_t<int*>, decltype(&custom_deleter)> smart_ptr(new int(10), custom_deleter);
std::cout << "Value: " << *smart_ptr << std::endl;

return 0;
}

 

重要说明

如果类型不是指针,std::remove_pointer_t 会保持其不变。

它可以处理 const、volatile 和 const volatilepointer, 在保留基础类型限定符的同时剥离 pointer。

为 std::remove_pointer_t 添加特殊功能是未定义的行为,应该避免。

Std::remove_pointer_t 是现代 C++ 中用于类型操作的强大工具,在模板密集型代码库中特别有用。

posted @ 2025-09-17 10:35  PKICA  阅读(9)  评论(0)    收藏  举报