chriskirk chriskirk - 1 year ago 89
C++ Question

C++ template for arrays and knowing their size

I have a bunch of structs like:

struct A { ... }
struct B { ... }
struct C { ... }

I want to devise a function that can accept arrays of these structs and iterate through each element of the array and call another function like:

template <typename T>
ostream& process(ostream& os, const T* array) {
// output each element of array to os (but how do we know the length?)

A a_array[10];


I cannot pass in the size of the array explicitly as the process function is actually operator<<() (I just used process for demonstration purposees)

Update: I cannot use any of the std containers here. It has to be an array unfortunately!

Answer Source

Array-to-pointer decay is really, really bad.

Fortunately, C++ has array references, which know their size.

template<typename T, size_t N> ostream& process(ostream& os, const T (&arr)[N]) {
    // use N
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download