Dan
Dan

Reputation: 2876

Using templates to pass array with N elements in C++

Here we pass a reference to an entire array using templates, and it compiles fine:

template <int N>
void test(int (&in)[N]){
}

int main(){
 int a[2] = {1,2};
 test(a);
 return 0;
}

But doing the same to pass a regular array doesn't work, the template can't figure out what N is on its own, why?

template <int N>
void test(int in[N]){
}

int main(){
 int a[2] = {1,2};
 test(a);
 return 0;
}

error: couldn't deduce template parameter 'N'

Upvotes: 1

Views: 350

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122228

It is not "doing the same way". When a function takes an array like this:

void foo( int x[] )

Then that is just a slightly obfuscated way to write this:

void foo( int* x)

Arrays decay to pointers when passed to functions. You cannot pass arrays by value.

You can pass arrays by reference and thats what your first code does. Maybe the template is confusing you. Consider that if you know the dimension you can write:

void test(int (&in)[2]){
}

Then in inside test will be a reference to an array with two elements, but if you pass a pointer then its just a pointer and information on the array size is lost.

Upvotes: 4

Jarod42
Jarod42

Reputation: 217145

C-arrays cannot be passed as value and decay to pointer, making N non deducible.

Upvotes: 2

Related Questions