gpt4 book ai didi

c++ - 为什么 std::iterator_traits 找不到 value_type?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:42:26 24 4
gpt4 key购买 nike

为什么我不能编译下一段代码?

#include <iterator>

struct test_iterator {
using value_type = int;
};

int main()
{
std::iterator_traits<test_iterator>::value_type a = 0;
return a;
}

好像三大编译器(msvc/gcc/clang)都编译不了这段代码。

据我所知,std::iterator_traits 的工作方式如下:

template <class T>
struct iterator_traits {
using value_type = typename T::value_type;
... // other memebers
};

这里有什么问题吗?

最佳答案

来自 iterator_traits ,从 C++17 开始:

"If Iterator does not have the five member types difference_type, value_type, pointer, reference, and iterator_category, then this template has no members by any of those names (std::iterator_traits is SFINAE-friendly)"

提供缺失的类型可以修复错误:Demo

如果迭代器满足某些概念,C++20 会添加新的方法来填充成员。

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

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