Why doesn't this template function call work inside this function?

arrays, c++, templates

Solution

If you want this to work, you need to make processArray be a template as well:

template <size_t size>
void processArray(const byte (&b)[size])
{
    // do some other stuff
}

C++ does not allow passing arrays by value. If you have a function like this:

void f(int a[5]);

It may look like you are passing an array by value, but the language has a special rule that says a parameter of this form is just another way of saying:

void f(int *a);

So the size of the array is not part of the type at all. This is behavior inhereted from C. Fortunately, C++ has references, and you can pass a reference to an array, like this:

void f(int (&a)[5]);

This way, the size of your array is preserved.

Now, the only remaining trick is to make the function generic, so it can work on any size array.

template <size_t n> void f(int (&a)[n]);

Now, new versions of the function that take references to arrays of different sizes can be generated automatically for you, and the size can be accessed through the template parameter.

Problem

The following code doesn't compile, I am trying to figure out how to calculate the size of an array that is passed into a function and can't seem to get the syntax correct. The error I am getting is : ``` Error 1 error C2784: 'size_t getSize(T (&)[SIZE])' : could not deduce template argument for 'T (&)[SIZE]' from 'const byte []' 16 1 sizeofarray ``` Here is the source code: ``` #include <cstdint> #include <stdio.h> template<typename T, size_t SIZE> size_t getSize(T (&)[SIZE]) { return SIZE; } typedef std::uint_fast8_t byte; void processArray(const byte b[]) { size_t size = getSize(b); // <- line 16 where error occurs // do some other stuff } int main(const int argc, const char* argv[]) { byte b[] = {1,2,3,4,5,6}; printf("%u\n", getSize(b)); processArray(b); return 0; } ```

Original source