0

I know that one can determine the size of a C-style array (allocated on stack) using

template <typename T, size_t N>
size_t arr_size(T(&)[N])
{
    return N;
}

This works fine. Now my question is why do we have to pass the array by reference? If we pass it by value,

template <typename T, size_t N>
size_t arr_size(T[N])
{
    return N;
}

the code does not compile, i.e. in

#include <iostream>

template <typename T, size_t N>
size_t arr_size(T[N])
{
    return N;
}

int main()
{
    int arr[10];
    std::cout << "Array has size: " << arr_size(arr) << std::endl;
}

we get error: no matching function for call to 'arr_size' std::cout << "Array has size: " << arr_size(arr) << std::endl; ^~~~~~~~ /Users/vlad/minimal.cpp:6:8: note: candidate template ignored: couldn't infer template argument 'N' size_t arr_size(T[N])

If we define

template <typename T, size_t N>
size_t arr_size(T(&)[N]) 

then it works.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 1
    When you take it by value, you're really taking a pointer. See [arrays](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c). – chris May 18 '14 at 01:22
  • Ohhh ok, got it, so it is decaying to a pointer... Thanks! – vsoftco May 18 '14 at 01:22
  • Actually, [this answer](http://stackoverflow.com/a/7439261/962089) in there covers the same scenario, so I'm going to close it as a dupe. – chris May 18 '14 at 01:26
  • 1
    There really not being any way to pass arrays by value is a big language quirk of C that one just gotta get used to. – AliciaBytes May 18 '14 at 01:28
  • 1
    @RaphaelMiedl, I suggest using `std::array` in C++11 and `boost::array` before that. They do what you would expect an array to do. – chris May 18 '14 at 01:30
  • Ok, thanks, did not find a previous answer, but thanks for posting the link. I see what's happening now. I know I can use `std::array`, was just curious though about the behaviour of my code snippet, especially because I was trying to understand how `std::begin` and `std::end` work on standard stack-allocated `C`-style arrays. – vsoftco May 18 '14 at 01:32

0 Answers0