如何通过std::pointer_traits在泛型底层操作中简化自定义指针类型?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1030个文字,预计阅读时间需要5分钟。
不能直接简化的内容可以改写为:
它的作用是提供一套标准接口:从任意指针类型中提取 element_type、difference_type、rebind 等元信息。这些不是凭空猜出来的,而是靠特化或默认推导。
- 如果你的自定义指针有
typedef T element_type和typedef U* pointer,std::pointer_traits会自动识别,无需特化 - 如果指针是模板类(如
MyPtr<t></t>),且你想支持rebind到其他类型,就必须显式特化std::pointer_traits<myptr>></myptr> - 裸指针(
T*)和std::shared_ptr都已预特化,你不用管
什么时候必须特化 std::pointer_traits?
当你定义的指针类型不满足默认推导规则时——典型场景是:没有公开 element_type,或 rebind 逻辑不能靠 template<class u> using rebind = MyPtr<u>;</u></class> 实现(比如带额外模板参数)。
本文共计1030个文字,预计阅读时间需要5分钟。
不能直接简化的内容可以改写为:
它的作用是提供一套标准接口:从任意指针类型中提取 element_type、difference_type、rebind 等元信息。这些不是凭空猜出来的,而是靠特化或默认推导。
- 如果你的自定义指针有
typedef T element_type和typedef U* pointer,std::pointer_traits会自动识别,无需特化 - 如果指针是模板类(如
MyPtr<t></t>),且你想支持rebind到其他类型,就必须显式特化std::pointer_traits<myptr>></myptr> - 裸指针(
T*)和std::shared_ptr都已预特化,你不用管
什么时候必须特化 std::pointer_traits?
当你定义的指针类型不满足默认推导规则时——典型场景是:没有公开 element_type,或 rebind 逻辑不能靠 template<class u> using rebind = MyPtr<u>;</u></class> 实现(比如带额外模板参数)。

