相关疑难解决方法(0)

使用模板获取数组的大小和结束地址

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

template<typename T, size_t N>
size_t arraylen( T(&)[N] )
{ return N; }
Run Code Online (Sandbox Code Playgroud)

我想把这个想法更进一步.

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.
}
Run Code Online (Sandbox Code Playgroud)

但是,对于我的生活,我无法获得编译的语法.我认为我缺少的一部分是我真的不明白这T(&)[N]意味着什么.

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

如何在仍然使用模板获取其大小的同时允许访问数组的地址?

c++ templates metaprogramming

2
推荐指数
1
解决办法
1678
查看次数

C++中的数组和长度

我试图将一个数组的长度作为参数传递给某个函数.代码如下所示:

double getAverage(int numbers[])
{
    int length = sizeof(numbers)/sizeof(numbers[0]);
    // here the result of the length is 1.
    int sum = 0;
    for (int i = 0 ; i < length ; i++)
    {
        sum += numbers[i];
    }
    return (double)sum / length;
}

int main()
{
    int numbers[8] = {1,2,3,4,5,6,7,8};
    //if I call here sizeof(numbers)/sizeof(numbers[0] the result will be 8 as it   
    //should be.
    cout << getAverage(numbers) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何通过引用获取作为函数参数传递的数组长度(虽然我知道每个数组都通过引用传递)?我知道在C/C++中找到数组长度存在很多问题,但是没有人能给我一些我正在寻找的答案.提前致谢.

c++ arrays

1
推荐指数
1
解决办法
384
查看次数

标签 统计

c++ ×2

arrays ×1

metaprogramming ×1

templates ×1