62 lines · cpp
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9// std::sort10 11#include <algorithm>12#include <iterator>13#include <type_traits>14#include <utility>15 16struct BadIter {17 struct Value {18 friend bool operator==(const Value& x, const Value& y);19 friend bool operator!=(const Value& x, const Value& y);20 friend bool operator< (const Value& x, const Value& y);21 friend bool operator<=(const Value& x, const Value& y);22 friend bool operator> (const Value& x, const Value& y);23 friend bool operator>=(const Value& x, const Value& y);24 friend void swap(Value, Value);25 };26 27 using iterator_category = std::random_access_iterator_tag;28 using value_type = Value;29 using reference = Value&;30 using difference_type = long;31 using pointer = Value*;32 33 Value operator*() const; // Not `Value&`.34 reference operator[](difference_type n) const;35 36 BadIter& operator++();37 BadIter& operator--();38 BadIter operator++(int);39 BadIter operator--(int);40 41 BadIter& operator+=(difference_type n);42 BadIter& operator-=(difference_type n);43 friend BadIter operator+(BadIter x, difference_type n);44 friend BadIter operator+(difference_type n, BadIter x);45 friend BadIter operator-(BadIter x, difference_type n);46 friend difference_type operator-(BadIter x, BadIter y);47 48 friend bool operator==(const BadIter& x, const BadIter& y);49 friend bool operator!=(const BadIter& x, const BadIter& y);50 friend bool operator< (const BadIter& x, const BadIter& y);51 friend bool operator<=(const BadIter& x, const BadIter& y);52 friend bool operator> (const BadIter& x, const BadIter& y);53 friend bool operator>=(const BadIter& x, const BadIter& y);54};55 56// Verify that iterators with incorrect `iterator_traits` are rejected. This protects against potential undefined57// behavior when these iterators are passed to standard algorithms.58void test() {59 std::sort(BadIter(), BadIter());60 //expected-error-re@*:* {{static assertion failed {{.*}}It looks like your iterator's `iterator_traits<It>::reference` does not match the return type of dereferencing the iterator}}61}62