Advertisement

How to have tamplates that only takes int[] ?

Started by September 10, 2017 06:13 AM
2 comments, last by MarcusAseth 7 years, 2 months ago

I was doing this experiment, code below

 


#include <iostream>
using namespace std;

template<typename T>
void decay_test(T& arr)
{
	cout << sizeof(arr) << endl;
	cout << "arr has " << sizeof(arr) / sizeof(*arr) << " elements" << endl;
}

int main()
{
	const auto size = 100;
	int arr[size];
	decay_test(arr);

	return 0;
}

output:

Quote

400
arr has 100 elements

Just wanted to see if it was possible to pass and array and it's size into a function with a single argument.

Seems it works, though how one would go about to make it in such a way that the template only takes in arrays of integers? :S

 


template <size_t N>
void f(int (&arr)[N])
{
	std::cout << N << std::endl;
}

For taking arbitrary array types, make the int a template parameter as well.

To make it is hell. To fail is divine.

Advertisement

That works beautifully, thanks Zao :)

 

This topic is closed to new replies.

Advertisement