jarrodhroberson
11/12/2012 - 3:33 PM

How to get the length of an array with a template as well as pass in an array to a function to get its length in the function.

How to get the length of an array with a template as well as pass in an array to a function to get its length in the function.

#include <cstdint>
#include <stdio.h>

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

typedef std::uint_fast8_t byte;

template <size_t SIZE>
size_t processArray(const byte (&b)[SIZE])
{
	return getSize(b);
}

int main(const int argc, const char* argv[])
{
	byte a[] = {1,2,3,4,5,6};
	printf("%u\n", processArray(a));
	byte b[1024];
	printf("%u\n", processArray(b));

	return 0;
}