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
I prefer the enum method suggested by [BCS](in Can this macro be converted to a function?)
This is because you can use it where the compiler is expecting a compile time constant. The current version of the language does not let you use functions results for compile time consts but I believe this coming in the next version of the compiler:
The problem with this method is that it does not generate a compile time error when used with a class that has overloaded the '*' operator (see code below for details).
Unfortunately the version supplied by 'BCS' does not quite compile as expected so here is my version:
#include
#include
#include
template
struct StructSize
{
private: static T x;
public: enum { size = sizeof(T)/sizeof(*x)};
};
template
struct StructSize
{
/* Can only guarantee 1 item (maybe we should even disallow this situation) */
//public: enum { size = 1};
};
struct X
{
int operator *();
};
int main(int argc,char* argv[])
{
int data[] = {1,2,3,4,5,6,7,8};
int copy[ StructSize::size];
std::copy(&data[0],&data[StructSize::size],©[0]);
std::copy(©[0],©[StructSize::size],std::ostream_iterator(std::cout,","));
/*
* For extra points we should make the following cause the compiler to generate an error message */
X bad1;
X bad2[StructSize::size];
}