As titled, the following code snippet doesn't work even I defined the type "iterator_category" and made it visible to the outside in the class definition, the expectation of the output should be '1' rather than '0'. How should I fix that?
struct Iter {
using iterator_category = std::random_access_iterator_tag;
};
int main(int argc, char **argv) {
std::cout << std::__has_iterator_typedefs<Iter>::value << std::endl; // output '0';
// std::cout << (typeid(std::iterator_traits<Iter>::iterator_category) == typeid(std::random_access_iterator_tag)) << std::endl;
return 0;
}
iterator_category
is not the only member type that a standard library compatible iterator should provide. If you take look at how __has_iterator_typedefs
is implemented , you'll see that it also checks for the presence of these member types: difference_type
, value_type
, reference
, and pointer
. Add all these, and then std::iterator_traits<Iter>::iterator_category
will return the category of your iterator.
struct Iter {
using iterator_category = std::random_access_iterator_tag;
using value_type = int;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using pointer = value_type*;
};
static_assert(std::is_same_v<std::iterator_traits<Iter>::iterator_category,
std::random_access_iterator_tag>);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.