gpt4 book ai didi

c++ - 为什么我不能从 iterator_traits 获取 value_type?

转载 作者:IT老高 更新时间:2023-10-28 21:39:25 25 4
gpt4 key购买 nike

我正在这样做:

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 .但是我得到了一个错误:

error C2039: value_type: is not a member of std::iterator_traits<_Ty *const >

这是 const 的问题吗?我需要去掉那个吗?

最佳答案

这里的问题在于行

const auto foo = cbegin(arr);

cbegin(arr) 将返回一个 int const * (指向 const int 的指针),因此将 const 应用于 >const auto foo 表示 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.

关于c++ - 为什么我不能从 iterator_traits 获取 value_type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com