Reference To Array Using Template Approach In C++

Reference To Array Using Template this technique saves all data about the underlying array.

This method is primarily reliant on array references, but leveraging templates optimizes our method. Because a reference to an array needs to know the size of the array, the template dependency calculates the length of the array automatically at the time of the function call so that it can be used to construct a reference.

Check out my post regarding the array <post-not-published-yet>

The template is used to determine template arguments in this case.

#include <iostream>
using namespace std;

template<size_t N>
void print(int (&a)[N]){
	for(int e: a){
		cout << e << endl;
	}
}

int main(){
	int a[] {1, 2, 3, 4, 5};
	print(a);
}

Output:

1
2
3
4
5

Here’s why we need template argument deduction: for the base to build an array reference so we may pass an array as a parameter.

  • Dual compiler’s perspective on array.
  • Reference to array.
  • How to Use references?
  • Is Array a type or just pointer to first element?
  • Are two arrays of different length same for compilers perspective?
  • Difference between Array and pointer.

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 253

Newsletter Updates

Enter your email address below to subscribe to our newsletter