Playing with templates, I implemented this one for iterating arrays:
template<class T, size_t size>
void iterate(T(&arr)[size], void(*fn)(T&)) {
for(size_t i=0; i<size; ++i) fn(arr[i]);
}
So I could iterate arrays like this
void printn(int& n) {
printf("%d\n",n);
}
int a[] = {3,-4,6,2};
iterate(a,printn);
Then I realized that I also need const iterator, so the first bad idea was to code
template<class T, class U, size_t size>
void iterate(T(&arr)[size], void(*fn)(U&)) {
for(size_t i=0; i<size; ++i) fn(arr[i]);
}
I know it is bad, but I wonder why this behavior:
void printn(int& n); // works
void printn(const int& n); // also works
void printn(short& n); // type mismatch
void printn(const short& n); // works
There is also an issue with lambdas:
iterate(a,[](int& n) { printf("%d\n",n); }); // type mismatch
So the question is Why the type mismatches and how to solve them?
I use 32bit MinGW 4.8.1 with -std=C++11
option.