deft_code
deft_code

Reputation: 59269

Use templates to get an array's size and end address

You can use templates to find the length of an array.

template<typename T, size_t N>
size_t arraylen( T(&)[N] )
{ return N; }

I'd like to take this idea one step further.

struct Foo
{
   template< typename T, size_t N >
   Foo( /* ??? */ ) : ptr(?), size(?) { }

   char* ptr;
   size_t size;
};

int main()
{
   Foo foo("test");

   const char bar[] = "test2";
   Foo foo2(bar);

   const char* baz = bar;
   Foo foo3(baz); // compiler error.
}

However, for the life of me I can't get the syntax to compile. I think part of what I'm missing is I don't really understand what the T(&)[N] means.

What does T(&)[N] mean?

How can I allow access to array's address while still grabbing its size with templates?

Upvotes: 2

Views: 1820

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

struct Foo
{
   template< typename T, size_t N >
   Foo(T(&array)[N]) : ptr(array), size(N) { }

   const char* ptr;
   size_t size;
};

array is a reference to an array of N T's. The same is true of the original code, but the parameter isn't given a name.

But this really isn't calculating the address at compile time. If you think about it, you'll realize this is impossible. If stack addresses were fixed, recursion (and many other algorithms) could never work.

Note that the last line:

Foo foo3(baz);

still won't work because baz is a pointer not an array.

Upvotes: 6

Related Questions