What is useful about a reference-to-array parameter?

后端 未结 6 1463
野的像风
野的像风 2020-11-29 20:52

I recently found some code like this:

typedef int TenInts[10];
void foo(TenInts &arr);

What can you do in the body of foo()

6条回答
  •  借酒劲吻你
    2020-11-29 21:08

    You can write a function template to find out the size of an array at compile time.

    template
    size_t array_size(E(&)[size])
    {
        return size;
    }
    
    int main()
    {
        int test[] = {2, 3, 5, 7, 11, 13, 17, 19};
        std::cout << array_size(test) << std::endl; // prints 8
    }
    

    No more sizeof(test) / sizeof(test[0]) for me ;-)

提交回复
热议问题