Re: "no matching function for call to 'begin(int&)'"
On Tuesday, October 1, 2013 10:10:08 PM UTC+2, Stefan Ram wrote:
[...]
Error: no matching function for call to 'begin(int&)'
[...]
Can I make C++ call my custom begin and end functions
for the loop above? As you can see, my first attempt
does not seem to work.
Built-in types don't have associated namespaces. So, there is no
argument-dependend lookup. For the purpose of lookup the for range
loops looks for begin/end member functions and if they are not
available looks for free begin/end functions via ADL where the
namespace ::std is always considered part of the associated namespaces
(so the for range loop works for raw arrays).
And secondly, begin and end are supposed to return things that are
iterator-like. If you want to write begin/end functions that work in
a for-range loop, the things returned by begin/end have to be usable
like iterators. That means operator++ advances it, operator* yields
the current value and ==/!= are needed for comparison.
Here's a quick sketch:
struct intiter
{
int value;
explicit intiter(int v) : value(v) {}
int operator*() const {return value;}
intiter& operator++() {++value; return *this;}
bool operator==(intiter that) const {return value==that.value;}
bool operator!=(intiter that) const {return value!=that.value;}
};
struct intrange
{
int beg_, end_;
intrange(int b, int e) : beg_(b), end_(e) {}
intiter begin() const {return intiter(beg_);}
intiter end() const {return intiter(end_);}
};
#include <iostream>
int main()
{
for (int i : intrange(0,5)) {
std::cout << i << std::endl;
}
}
Cheers!
sg