views:

663

answers:

8

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?

+5  A: 

If you are on a Microsoft only platform, you can take advantage of the _countof macro. This is a non-standard extension which will return the count of elements within an array. It's advantage over most countof style macros is that it will cause a compilation error if it's used on a non-array type.

The following works just fine (VS 2008 RTM)

static int ARRAY[5];
enum ENUM{N=_countof(ARRAY)};

But once again, it's MS specific so this may not work for you.

JaredPar
_countof is implemented as a macro for C and a typesafe inline function for C++; in other words, it's identical to the question's (1) and (2).
Josh Kelley
+4  A: 

You can't solve it in general, thats one the reasons for array wrappers like boost array (plus stl-style behaviour of course).

Georg Fritzsche
+5  A: 

In C++1x constexpr will get you that:

template <typename T, size_t N>
constexpr size_t countof(T(&)[N])
{
    return N;
}
dalle
The same can be written in C++99, and in most cases the compiler will optimize away the call.
David Rodríguez - dribeas
But in C++98 it can't be used where a constant expression is expected
jalf
+13  A: 

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"

Adisak
Note -- for your two issues:#1) Macros : you do not have to use the countof() macro, you can just use sizeof(_ArraySizeHelper( array )) but the countof() macro is a simplification.#2) enums -- it works with enums in the above example
Adisak
+1. This has the added benefit of being typesafe (i.e., it will fail to compile if you pass a pointer instead of an array).
Josh Kelley
Impressive solution.
Viktor Sehr
Its a nice solution, but not completely general: "it doesn’t work with types defined inside a function"
Georg Fritzsche
@gf: Templates in general don't work so well for types defined inside a function. In fact, it doesn't work for STL -- the following won't compile under GCC: void test() { struct foo{ int a; }; std::vector<foo> b; } You're much better off using a namespace (or anonymous namespace) if you need to create a class that is only going to be used by one function and you need to use templates on that class.
Adisak
+6  A: 

The best I can think of is this:

template <class T, std::size_t N>
char (&sizeof_array(T (&a)[N]))[N];

// As litb noted in comments, you need this overload to handle array rvalues
// correctly (e.g. when array is a member of a struct returned from function),
// since they won't bind to non-const reference in the overload above.
template <class T, std::size_t N>
char (&sizeof_array(const T (&a)[N]))[N];

which has to be used with another sizeof:

int main()
{
    int a[10];
    int n = sizeof(sizeof_array(a));
    std::cout << n << std::endl;
}

[EDIT]

Come to think of it, I believe this is provably impossible to do in a single "function-like call" in C++03, apart from macros, and here's why.

On one hand, you will clearly need template parameter deduction to obtain size of array (either directly, or via sizeof as you do). However, template parameter deduction is only applicable to functions, and not to classes; i.e. you can have a template parameter R of type reference-to-array-of-N, where N is another template parameter, but you'll have to provide both R and N at the point of the call; if you want to deduce N from R, only a function call can do that.

On the other hand, the only way any expression involving a function call can be constant is when it's inside sizeof. Anything else (e.g. accessing a static or enum member on return value of function) still requires the function call to occur, which obviously means this won't be a constant expression.

Pavel Minaev
Remove the `const` to make it more generic.
dalle
Pavel Minaev
I like to use identity in these case, because it greatly improves readability: `template<typename T, size_t N> typename identity<char[N]>::type ` . For the `const` removal - this actually decreased genericity. Because now you cannot accept rvalue arrays anymore (non-const array reference won't bind to rvalue arrays): `struct A { int b[2]; }; .. sizeof_array(A().b); // doesn't work if it's not const!`. Notice that this rvalue array is not const itself, so deduction won't put const either. Note that this isn't a big issue - but arguably it's less generic i think.
Johannes Schaub - litb
The rvalue array isn't `const` itself, but its element type is `const`, so why wouldn't it be deduced? As a side note, both MSVC and (more reassuringly) Comeau are able to deduce `T` as `const int` when passing `const int a[10]` just fine.
Pavel Minaev
If the element type of an array is const, the array is const too, it propagates up (given `typedef int a[10];`, then `a const` is the same type as `int const[10]`) . In any case, surely with `int const a[10]; sizeof_array(a);` it works. But `a` is an lvalue, and its type is `int const[a]`, so `T` is `int const`. In case of `struct A { int b[2]; }; ... sizeof_array(getAnA().b);` the passed array is an rvalue, and its type is `int[2]`, so `T` is `int` - but non-const references won't bind to rvalues. Surely rvalue arrays are seldom, but nonetheless, genericity decreased instead of increased :)
Johannes Schaub - litb
Yeah, you're right regarding rvalue arrays... looks like this really needs two overloads to be fully generic. I'll add that.
Pavel Minaev
Johannes Schaub - litb
+1  A: 

It appears not to be possible to obtain the sizeof array as a compile-time constant without a macro with current C++ standard (you need a function to deduce the array size, but function calls are not allowed where you need a compile-time constant). [Edit: But see Minaev's brilliant solution!]

However, your template version isn't typesafe either and suffers from the same problem as the macro: it also accepts pointers and notably arrays decayed to a pointer. When it accepts a pointer, the result of sizeof(T*) / sizeof(T) cannot be meaningful.

Better:

template <typename T, size_t N>
size_t sizeof_array(T (&)[N]){
    return N;
}
UncleBens
ah, didnt think about that
Viktor Sehr
+2  A: 

Without C++0x, the closest I can get is:

#include <iostream>

template <typename T>
struct count_of_type
{
};


template <typename T, unsigned N>
struct count_of_type<T[N]> 
{
    enum { value = N };
};

template <typename T, unsigned N>
unsigned count_of ( const T (&) [N] )
{
    return N;
};


int main ()
{
    std::cout << count_of_type<int[20]>::value << std::endl;
    std::cout << count_of_type<char[42]>::value << std::endl;

    // std::cout << count_of_type<char*>::value << std::endl; // compile error

    int foo[1234];

    std::cout << count_of(foo) << std::endl;

    const char* bar = "wibble";

    // std::cout << count_of( bar ) << std::endl; // compile error

    enum E1 { N = count_of_type<int[1234]>::value } ;

    return 0;
}

which either gives you a function you can pass the variable to, or a template you can pass the type too. You can't use the function for a compile time constant, but most cases you know the type, even if only as template parameter.

Pete Kirkham
With C++0x, you _can_ use a function for a compile time constant, if you declare it `constexpr` - as other answers have pointed out.
Pavel Minaev
Having read that post I put "Without C++0x" at the start of mine to show that I wasn't using that technique, but one which will work with current compilers.
Pete Kirkham
The compile-time constant version looks a bit pointless, though. Why would you ever go through the trouble of typing count_of_type<int[20]>::value if you have to know the size is 20? :)
UncleBens
You might want count_of_type<T>::value where T is a template parameter, but I agree it's liable to be rare.
Pete Kirkham
+2  A: 

It's not exactly what you're looking for, but it's close - a snippet from winnt.h which includes some explanation of what the #$%^ it's doing:

//
// RtlpNumberOf is a function that takes a reference to an array of N Ts.
//
// typedef T array_of_T[N];
// typedef array_of_T &reference_to_array_of_T;
//
// RtlpNumberOf returns a pointer to an array of N chars.
// We could return a reference instead of a pointer but older compilers do not accept that.
//
// typedef char array_of_char[N];
// typedef array_of_char *pointer_to_array_of_char;
//
// sizeof(array_of_char) == N
// sizeof(*pointer_to_array_of_char) == N
//
// pointer_to_array_of_char RtlpNumberOf(reference_to_array_of_T);
//
// We never even call RtlpNumberOf, we just take the size of dereferencing its return type.
// We do not even implement RtlpNumberOf, we just decare it.
//
// Attempts to pass pointers instead of arrays to this macro result in compile time errors.
// That is the point.
//
extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];

#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))

The RTL_NUMBER_OF_V2() macro ends up being used in the more readable ARRAYSIZE() macro.

Matthew Wilson's "Imperfect C++" book also has a discussion of the techniques that are used here.

Michael Burr
I like the last line of the comment: "That is the point."
James McNellis