Issue
I have some simple code
#include<iterator>
int main() {
int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
auto a = std::begin(y);
std::cout << *a << std::endl;
return 0;
}
Which prints out 1
as expected.
However if I do this :
void checkNested(int val [10]) {
auto a = std::begin(val);
std::cout << *a << std::endl;
}
int main() {
int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
checkNested(y);
return 0;
}
I get compilation failures from both clang++
and g++
.
From clang++
specifically I get:
auto a = std::begin(input);
^~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/initializer_list:89:5: note: candidate template ignored: could not match 'initializer_list<type-parameter-0-0>' against 'int *'
begin(initializer_list<_Tp> __ils) noexcept
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:48:5: note: candidate template ignored: substitution failure [with _Container = int *]: member reference base type 'int *' is not a structure or union
begin(_Container& __cont) -> decltype(__cont.begin())
^ ~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:58:5: note: candidate template ignored: substitution failure [with _Container = int *]: member reference base type 'int *const' is not a structure or union
begin(const _Container& __cont) -> decltype(__cont.begin())
^ ~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:87:5: note: candidate template ignored: could not match '_Tp [_Nm]' against 'int *'
begin(_Tp (&__arr)[_Nm])
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:104:31: note: candidate template ignored: could not match 'valarray<type-parameter-0-0>' against 'int *'
template<typename _Tp> _Tp* begin(valarray<_Tp>&);
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:105:37: note: candidate template ignored: could not match 'valarray<type-parameter-0-0>' against 'int *'
template<typename _Tp> const _Tp* begin(const valarray<_Tp>&);
Just wanna know if there's something really obvious I'm missing here since I expected them to function the same. Thanks
Solution
An array can't be passed by value, so your array decays into a pointer when passed to checkNested()
, and std::begin()
is not defined for a pointer, hence the error.
void checkNested(int val [10])
is just syntax sugar for void checkNested(int *val)
.
If you pass the array by reference instead, then the code will work:
void checkNested(int (&val) [10])
Answered By - Remy Lebeau