Author Topic: Arraysize  (Read 1709 times)

Offline Hooman

  • Administrator
  • Hero Member
  • *****
  • Posts: 4955
Arraysize
« on: February 17, 2009, 12:33:42 AM »
I stumbled across this today, and thought some people here might find this interesting. Instead of using sizeof, to determine the number of elements in an array (such as in the OP2Helper files in the SDK), you can use templates.


Code: [Select]
#include <stdio.h>

template<typename T, int size> int ArraySize(T (&)[size]) {return size;};

int main()
{
int array[] = { 1, 2, 3, 4, 5 }; // Implicit size of 5
printf("Array size: %i\n", ArraySize(array)); // Implicit template parameters

return 0;
}

Unfortunately, this doesn't work in MSVC 6.0. Works fine when I tested it with g++ though.


As neat as templates can be, I've noticed they're probably the least well supported part of the C++ spec. Definately an overly complicated language.

Btw, the "T (&)[size]" part might be easier read as "T (&dummy)[size]", except the parameter name was omitted. You only actually need to specify the parameter type in C++, not give it a name, but giving parameters a name usually makes the function prototype easier to read, and is only necessary in the function definition if you actually want to use the parameter.