使用模板获取数组的大小和结束地址 [英] Use templates to get an array's size and end address

查看:121
本文介绍了使用模板获取数组的大小和结束地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用模板来查找数组的长度。

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.
}

然而,对于我的生活我无法获得语法编译。我认为我缺少的部分是我不真正明白 T(&)[N] 的含义。

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.

T(&)[N] 是什么意思?

访问数组的地址,同时仍然使用模板获取其大小?

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

推荐答案

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

   const char* ptr;
   size_t size;
};

数组 N T的。原始代码也是如此,但是参数没有给出一个名称。

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.

注意最后一行:

Foo foo3(baz);

仍然无法运作,因为 baz 一个不是数组的指针。

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

这篇关于使用模板获取数组的大小和结束地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆