4

Consider this piece:

template <int N> void fill_with_magic(array<int, N>& whatever){
    for(int i = 0; i < N; i++){
        whatever[i] = magic(i, N);
    }
}

I call it by specific instance so for array of 3 I would have to do:

array<int, 3> some_array_of_3;
fill_with_magic<3>(some_array_of_3);

But do I really have to write <3>? Compiler already knows the array size so theoretically it could of infer the right instance based on that size. Can I really make it do that?

akalenuk
  • 3,815
  • 4
  • 34
  • 56

1 Answers1

6

The problem is the deduction of the argument: the second template argument of a std::array is not an int so the deduction doesn't take place because it requires a conversion.

You should define your method as

template <array<int, 0>::size_type N> void fill_with_magic(array<int, N>& whatever){
  for(int i = 0; i < N; i++){
    whatever[i] = magic(i, N);
  }
}

So that you are correctly expecting a array<int,0>::size_type as the argument, which will then be correctly deduced. Actually I think most of the implementation use size_t but this should be more portable (unless std::array<T, 0> gets a special specialization).

Jack
  • 131,802
  • 30
  • 241
  • 343