While refactoring code and ridding myself of all those #defines that we\'re now taught to hate, I came across this beauty used to calculate the number of elements in a struc
Answered in detail here: Array Size determination Part 1 and here: Array Size determination Part 2.
Edit: From Doug's code
template <typename T>
uint32_t StructSize() // This might get inlined to a constant at compile time
{
return sizeof(T)/sizeof(*T);
}
// or to get it at compile time for shure
class StructSize<typename T>
{
enum { result = sizeof(T)/sizeof(*T) };
}
I've been told that the 2nd one doesn't work. OTOH something like it should be workable, I just don't use C++ enough to fix it.
A page on C++ (and D) templates for compile time stuff
xtofl has the right answer for finding an array size. No macro or template should be necessary for finding the size of a struct, since sizeof() should do nicely.
I agree the preprocessor is evil, but there are occasions where it is the least evil of the alternatives.
Yes it can be made a template in C++
template <typename T>
size_t getTypeSize()
{
return sizeof(T)/sizeof(*T);
}
to use:
struct JibbaJabba
{
int int1;
float f;
};
int main()
{
cout << "sizeof JibbaJabba is " << getTypeSize<JibbaJabba>() << std::endl;
return 0;
}
See BCS's post above or below about a cool way to do this with a class at compile time using some light template metaprogramming.
Windows specific:
There is the macro _countof()
supplied by the CRT exactly for this purpose.
A link to the doc at MSDN
Simplfying @KTC's, since we have the size of the array in the template argument:
template<typename T, int SIZE>
int arraySize(const T(&arr)[SIZE])
{
return SIZE;
}
Disadvantage is you will have a copy of this in your binary for every Typename, Size combination.