简体   繁体   English

如果大小未知,如何通过引用传递一维数组作为参数?

[英]How to pass a single-dimensional array as an argument by reference if the size is unknown?

I know that if you want to pass an array by reference with a known size you use 我知道如果你想通过引用传递一个你已经使用的已知大小的数组

void add(char (&arr)[60])

But i only know that the array will be size between 1 and 60 inclusive. 但我只知道阵列的大小介于1到60之间。 Any way to do this? 有什么办法吗?

You can use a template to match any type and any size, and a static_assert to check the size of the array being passed at compile-time : 您可以使用模板匹配任何类型和任何大小,并使用static_assert检查在编译时传递的数组的大小:

template<typename T, std::size_t N>
void add(T (&arr)[N])
{
    static_assert(N <= 60, "wrong size");
    // ...
}

Demo 演示

other option , without using templates : 其他选项,不使用模板:

void add(char* arr , int size);

Remember that ad-hoc array names are "decaying" to be a pointer to the first element , so one-dimensional array can be passes as a pointer. 请记住,ad-hoc数组名称“衰减”为指向第一个元素的指针,因此一维数组可以作为指针传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM