使数组成为 c++ 函数的可选参数
Make an array an optional parameter for a c++ function
在 c++ 中,你可以像这样将参数设置为可选:
void myFunction(int myVar = 0);
如何使用数组执行此操作?
void myFunction(int myArray[] = /*What do I put here?*/);
您可以使用nullptr
或指向全局 const 数组的指针来表示默认值:
void myFunction(int myArray[] = nullptr ) {
// ^^^^^^^
}
这是因为当用作函数参数时int myArray[]
类型调整为int*
指针。
默认参数必须具有静态链接(例如,是全局参数)。下面是一个示例:
#include <iostream>
int array[] = {100, 1, 2, 3};
void myFunction(int myArray[] = array)
{
std::cout << "First value of array is: " << myArray[0] << std::endl;
// Note that you cannot determine the length of myArray!
}
int main()
{
myFunction();
return 0;
}
如果默认数组足够小(注意:它可以小于实际数组类型的大小),因此复制它不是问题,那么(自 C++11 以来)std::array
可能是最具表现力的"C++式"风格(正如 Ed Heal 在评论中暗示的那样)。除了每个无参数f()
调用的复制负担之外,使用默认值,数组本身具有与内置类 C 数组相同的性能属性,但它不需要一个笨拙的、单独定义的默认变量:
#include <array>
// Just for convenience:
typedef std::array<int, 3> my_array;
void f(const my_array& a = {1, 2, 3});
(注意:通过 const ref. 传递至少在那些明确传递参数的情况下会避免复制。
好吧,在现代C++ 17 中,您可以使用std::optional
.
std::optional<std::array<int,4>> oa;
// ...
if ( oa )
{
// there is content in oa
*oa // get the content
}
else
{
// there is no content inside oa
}
我使用 std::array
作为数组的表示,但您也可以使用原始数组、向量等。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类