Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't std::iterator_traits find value_type?

Why can't I compile next code?

#include <iterator>

struct test_iterator {
    using value_type = int;
};

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

It seems that all three major compilers(msvc/gcc/clang) cannot compile this code.

As far as I know, std::iterator_traits works like:

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

What's wrong here?

like image 503
xylosper Avatar asked Apr 11 '17 10:04

xylosper


1 Answers

From iterator_traits, since 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)"

Providing the missing types fixes the error: Demo

C++20 adds new ways to fill members if iterator satisfies some concepts.

like image 109
Jarod42 Avatar answered Oct 15 '22 11:10

Jarod42