Compile time sizeof_array without using a macro
c++, metaprogramming, puzzle
Solution
Try the following from here:
template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define mycountof( array ) (sizeof( _ArraySizeHelper( array ) ))
int testarray[10];
enum { testsize = mycountof(testarray) };
void test() {
printf("The array count is: %d\n", testsize);
}
It should print out: "The array count is: 10"
Problem
This is just something that has bothered me for the last couple of days, I don't think it's possible to solve but I've seen template magic before. Here goes: To get the number of elements in a standard C++ array I could use either a macro (1), or a typesafe inline function (2): (1) ``` #define sizeof_array(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0])) ``` (2) ``` template <typename T> size_t sizeof_array(const T& ARRAY){ return (sizeof(ARRAY)/sizeof(ARRAY[0])); } ``` As you can see, the first one has the problem of being a macro (for the moment I consider that a problem) and the other one has the problem of not being able to get the size of an array at compile time; ie I can't write: ``` enum ENUM{N=sizeof_array(ARRAY)}; ``` or ``` BOOST_STATIC_ASSERT(sizeof_array(ARRAY)==10);// Assuming the size 10.. ``` Does anyone know if this can be solved? Update: This question was created before constexpr was introduced. Nowadays you can simply use: ``` template <typename T> constexpr auto sizeof_array(const T& iarray) { return (sizeof(iarray) / sizeof(iarray[0])); } ```