I very rarely use C-arrays myself but I came up with the following bit of code while trying to answer someone else's question:
#include <cstddef>
template <std::size_t n>
class A {
public:
explicit A(const int (&arr) [n]) : arr_(arr) { }
private:
const int arr_ [n];
};
int main(int, char**) {
const int arr [3] = { 1, 2, 3 };
A<3> a (arr); // (1)
return 0;
}
It doesn't compile and I don't expect it to:
<source>:6:38: error: array initializer must be an initializer list
explicit A(const int (&arr) [n]) : arr_(arr) { }
^
<source>:14:8: note: in instantiation of member function 'A<3>::A' requested here
A<3> a (arr);
I don't expect it to compile for the same reason the following doesn't compile:
int main(int, char**) {
const int arr_a [3] = { 1, 2, 3 };
const int arr_b [3] = arr_a;
return 0;
}
Here's the compilation error:
<source>:3:13: error: array initializer must be an initializer list
const int arr_b [3] = arr_a;
^
But if you in the first code block comment out the line marked (1)
it compiles. As if, as I understand it, there's some way to call A::A(const int (&) [n])
that's valid. In my mind, even trying to initialise arr_
with arr
is wrong.
Why does the first code block compile if you comment out the line marked (1)
? Is there a way to call A::A(const int (&) [n])
that's valid?