In dealing with range for in C++ 17 standard, the end expression type may be different than the begin expression type, which allows for the range be delimited by a predicate. I have been trying to come up with an example with no success so far.
Say that we want the range for to iterate until the value pointed to by the iterator is greater than some value. How can we define a suitable end function to test for this?
// Don't do this at home kids
/// \todo remove if avaiable
#ifndef __cpp_lib_ranges
namespace std {
struct default_sentinel_t { };
inlineconstexpr default_sentinel_t default_sentinel{};
}
#endif
class IterateUntilFound {
public:
IterateUntilFound(const std::vector<int>& values, int stop_value)
: values(values), stop_value(stop_value)
{
}
intoperator*() const {
return values[idx];
}
voidoperator++() {
idx++;
}
/**
* Loop keep runinng as lone this returns true.
*/
booloperator!=(std::default_sentinel_t) const {
if(idx >= values.size()) returnfalse;
return values[idx] != stop_value;
}
/**
* \note These member functions enable the use of Stopper with range-based for loops.
*/
const IterateUntilFound& begin() constnoexcept {
return *this;
}
/**
* Returns a std::default_sentinel_t, which serves as the end iterator.
* \note These member functions enable the use of Stopper with range-based for loops.
*/
std::default_sentinel_t end() constnoexcept {
return std::default_sentinel;
}
private:
const std::vector<int>& values;
int stop_value=0;
size_t idx=0;
};
int main() {
std::vector<int> values {1,4,2,3,5};
std::cout << "Stop at 3\n";
for(auto v : IterateUntilFound(values,3)) {
std::cout << v << " ";
}
}
This is a complete rewrite and the example does not address the issues I was looking for. Thanks for the input but maybe I wasn't clear.
I am looking how to define an end() function for the dummy_array template that can be anything (could test any condition to end the iteration)...
I now realize that my