0

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.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 2
    In the first list of examples `short` and `int` are different types and rvalues can't bind to a non-const reference. Unless `printn` is expected to modify the value you should be passing by `const` reference anyway. – Captain Obvlious Oct 31 '14 at 10:48
  • 1
    I'm not sure how/of lambdas can/do degrade to a function pointer. But forcing seems to help `+[](...` by adding the unary `+`. – Niall Oct 31 '14 at 10:51
  • @CaptainObvlious Ok, but why they can't bind to non-const reference and *can* bind to const reference? Could you please point me the right place in manual? – Jan Turoň Oct 31 '14 at 10:53
  • @Niall uhh, I have never seen that unary `+` in front of lambda before. What does this black magic do? – Jan Turoň Oct 31 '14 at 10:54
  • 1
    @JanTuroň. It "forces" the function pointer conversion; http://stackoverflow.com/a/18889029/3747990 and http://stackoverflow.com/q/17822131/3747990 – Niall Oct 31 '14 at 11:01
  • 2
    It's covered in section dcl.init.ref/5 of the C++ Standard. – Captain Obvlious Oct 31 '14 at 11:06

0 Answers0