如何在方法中为向量设置默认值



我有一个场景,我需要添加一个矢量作为输入/输出[引用]参数到现有的遗留代码。为了避免任何错误,我需要将其设置为默认参数。

有人可以建议如何添加一个矢量作为默认参数的方法。事实上,我怀疑这是否可能。此外,如果这是可能的,应该用什么值初始化向量?

我建议重载这个方法:

void foo(double otherParameter);
void foo(double otherParameter, std::vector<int>& vector);
inline void foo(double otherParameter)
{
    std::vector<int> dummy;
    foo(otherParameter, dummy);
}

另一种设计,明确地说vector是一个可选的输入/输出参数,是:

void foo(double parameter, std::vector<int>* vector = 0);

是的,一个原始指针——我们没有获得它的所有权,所以实际上不需要智能指针。

不能这样做,因为可变左值引用不会绑定到右值。要么使用const并放弃参数的out部分,这样您就可以为其分配默认值,要么使用可变左值引用并强制调用者传递一些内容。

编辑:或者你可以写一个重载——我没有考虑过这个。至少在一个签名中是行不通的。

您可以为遗留调用添加另一个重载。

void f(int param)
{
    std::vector<type> dummy;
    f(param, dummy);   // call the modified function
}

使用指针:

void foo(legacy_parameters, std::vector<int>* pv = 0);

如果默认形参必须为非const引用类型,则可以这样做:

//original function
void f(std::vector<int> & v) //non-const reference
{
      //...
}
//just add this overload!
void f()
{
     std::vector<int> default_parameter;
     //fill the default_parameter
     f(default_parameter);
}

如果默认形参不是非const引用,则可以这样做:

void f(std::vector<int> v = std::vector<int>()); //non-reference
void f(const std::vector<int> & v = std::vector<int>()); //const reference

我想它应该是这样的,但是它很难看。

void SomeFunc(int oldParams,const vector<int>& v = vector<int>())
{
vector<int>& vp = const_cast<vector<int>& >(v);
..
..
}

最新更新