mikejsavage.co.uk / blog

RSS feed

31 Oct 2019 / C++ tricks: member array count

I recently wanted to make an array with the same size as some other array. Normally I would use ARRAY_COUNT, But this time the reference array was a struct member, and I was in a context where I had no struct instance I could use.

So this:

struct A {
        int a[ 4 ];
};

struct B {
        int b[ ??? ];
};

The solution is to use C++’s “pointer to data member” functionality:

template< typename T, typename M, size_t N >
constexpr size_t ARRAY_COUNT( M ( T::* )[ N ] ) {
       return N;
}

struct B {
        int b[ ARRAY_COUNT( &A::a ) ];
};

Weird but it works.