C ++ 11:如何获取指针或迭代器指向的类型? [英] C++11: How to get the type a pointer or iterator points to?

查看:110
本文介绍了C ++ 11:如何获取指针或迭代器指向的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,假设我写 template< class Pointer>类Foo ,我想在类中声明 typedef 类型 * p p 的类型 Pointer

To be more specific, suppose I am writing template<class Pointer> class Foo and I want to declare a typedef inside the class for the type that *p would have if p were of type Pointer.

在C ++ 03中,据我所知,唯一的方法是使用

In C++03, as far as I am aware, the only way to do this is with something like

typename std::iterator_traits<Pointer>::reference

此方法的缺点是它不工作如果 Pointer 是一些自定义的迭代器类型,并且作者忘了扩展 std :: iterator 或以其他方式定义 std :: iterator_traits 专业化。

The disadvantage of this method is that it won't work if Pointer is some custom iterator type and the author forgot to extend std::iterator or otherwise define a std::iterator_traits specialization.

在C ++ 11中,我的同事建议

In C++11, my colleague suggested

decltype(*Pointer())

但是如果 Pointer 不是默认构造的,所以他将此修改为

But this won't work if Pointer is not default-constructible, so he amended this to

decltype(**(Pointer*)0)

它工作,但后来我认为它看起来有点iffy,因为它涉及一个空指针的解引用,因此可能不符合标准。

I tried this, and it worked, but then I thought that it looked a bit iffy because it involves the dereference of a null pointer, and thus might not be standards-compliant.

我们可以做更好?

推荐答案

你应该谨慎对待一个空指针,但事实是这里确定! decltype 不会评估其操作数,因此取消引用内部的空指针是完全有效的。

You're right to be cautious about dereferencing a null pointer, but the fact is that it's ok here! decltype does not evaluate its operand, so dereferencing a null pointer inside is perfectly valid.

,是在C ++ 11中< utility> 中引入的 std :: declval

The proper solution, however, is std::declval, introduced inside <utility> in C++11:

decltype(*std::declval<Pointer>())

这篇关于C ++ 11:如何获取指针或迭代器指向的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆