C++11:如何获取指针或迭代器指向的类型
C++11: How to get the type a pointer or iterator points to?
更具体地说,假设我正在编写template<class Pointer> class Foo
,并且我想在类中为*p
类型声明一个typedef
,如果p
类型为Pointer
类型。
据我所知,在 C++03 中,做到这一点的唯一方法是使用类似的东西
typename std::iterator_traits<Pointer>::reference
此方法的缺点是,如果Pointer
是某种自定义迭代器类型,并且作者忘记扩展std::iterator
或以其他方式定义std::iterator_traits
专用化,则此方法不起作用。
在 C++11 中,我的同事建议
decltype(*Pointer())
但是如果Pointer
不是默认可构造的,这将不起作用,所以他将其修改为
decltype(**(Pointer*)0)
我试过这个,它奏效了,但后来我认为它看起来有点不稳定,因为它涉及空指针的取消引用,因此可能不符合标准。
我们能做得更好吗?
您对取消引用空指针持谨慎态度是对的,但事实是这里没关系! decltype
不计算其操作数,因此取消引用内部的空指针是完全有效的。
然而,正确的解决方案是 std::declval
,在 C++11 中引入<utility>
:
decltype(*std::declval<Pointer>())
在 C++03 中,您可以编写一个简单的结构,它将从给定类型中删除所有指针:
template<typename T>
struct ActualType { typedef T type; };
template<typename T>
struct ActualType<T*> { typedef typename ActualType<T>::type type; };
如果您通过int*
或int**
,那么最终ActualType<T>::type
将归结为int
。
这是一个演示;
在 C++11 中,您可以使用std::remove_pointer
using PType = std::remove_pointer<Pointer>::type;
执行迭代器特征,SFINAE
回退到取消引用。
与其取消引用 null,不如创建一个返回 std::decay<T>&
然后取消引用该模板函数。
相关文章:
- 如何在c++迭代器类型中包装std::chrono
- 定义模板参数的迭代器类型
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- C++不兼容的迭代器类型
- 如何推导 std::高级迭代器类型?
- 在 stl 容器包装器中定义迭代器类型
- 矢量迭代器类型未知
- STD ::向量迭代器类型和允许的操作
- 检查容器模板类中的迭代器类型
- 如何断言模板参数的类型 STL 迭代器类型
- 检测容器是否具有迭代器类型
- 由set2.begin()返回的迭代器类型
- 序列容器的迭代器类型是什么?
- 如何推断嵌套最多的迭代器类型
- 为什么迭代器类型与矢量容器中的 value_type * 不匹配
- ISO C++禁止声明没有自动迭代器类型的“it”
- 使用的迭代器类型错误
- 列表的迭代器类型
- 如何打印迭代器类型列表<pair<int,int>>::iterator itrator it指向的元素
- 为什么 void* 不是迭代器类型?