为什么我不能从iterator_traits获得value_type?
Why can't I get value_type from iterator_traits?
我正在这样做:
const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
const auto foo = cbegin(arr);
const typename iterator_traits<decltype(foo)>::value_type bar = 1;
我本来希望bar
有类型 int
.但相反,我收到一个错误:
错误 C2039:
value_type
: 不是std::iterator_traits<_Ty *const >
的成员
这是我需要剥离它或其他东西const
的问题吗?
这里的问题是行
const auto foo = cbegin(arr);
cbegin(arr)
将返回一个int const *
(指向 const int 的指针),因此使用 const auto foo
将const
应用于该foo
意味着是一个int const * const
(指向 const int 的 const 指针)
std::iterator_traits
只专门用于T*
或T const*
因此给它一个T* const
失败,因为没有有效的专业化。
您可以通过删除 bar
声明中的恒定性来解决此问题
const typename std::iterator_traits<std::remove_cv_t<decltype(foo)>>::value_type
或者您可以将foo
更改为
auto foo = std::cbegin(arr);
如果你对它不const
没意见.
确实const
是有问题的,你基本上是这样做的:
std::iterator_traits<const int* const>::value_type // incorrect due to the last const
您可以通过将其更改为
std::iterator_traits<const int*>::value_type // Correct
您可以使用std::decay
或std::remove_cv
const typename std::iterator_traits<std::remove_cv_t<decltype(foo)>>::value_type
(如果相关,请从foo
中删除const
)。
声明
一个常量限定的迭代器const auto foo = cbegin(arr);
是值得怀疑的。对于无法应用operator++()
的迭代器,您有什么用?此外,迭代器要求类型int const *const
是可复制的;因此,变量foo
不满足迭代器要求。所以严格来说,foo
不是迭代器。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 如何从C++中的依赖类型中获得它所依赖的类型
- 欧拉项目#8答案是大以获得有效答案
- 如何使用C/C++在MacOSX中获得键盘布局
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 如何在不产生任何垃圾的情况下获得C中的像素
- 有没有一种方法可以在编译时获得作用域类名
- 如何在C++中获得"静态纯虚拟"功能?
- 如何设置一个范围来提取我想要获得的信息
- 在多次运行中获得一致的callgrind输出
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 未获得字符串中的预期输出
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- Qt:当QListView获得新条目时,如何更新QStringList
- 如何在卷曲中获得卷曲/卷曲.h?
- 使用可变宏时获得"Error: #28: expression must have a constant value "