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

一笑奈何 提交于 2019-12-28 07:06:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4073276/use-templates-to-get-an-arrays-size-and-end-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!