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

时间:2011-08-04 14:31:47

标签: c++

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

有人可以建议如何将矢量作为默认参数添加到方法中。如果可能的话我真的很怀疑。此外,如果这是可能的,那么矢量应该使用什么样的值?

6 个答案:

答案 0 :(得分:5)

我建议重载方法:

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是/ out参数中的选项,是:

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

是的,一个原始指针 - 我们没有取得它的所有权,因此不需要智能指针。

答案 1 :(得分:3)

你不能这样做,因为可变的左值引用不会绑定到右值。您可以使用const并放弃参数的外部部分,这样您就可以为其指定默认值,或者使用可变左值引用并强制调用者传入内容。

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

答案 2 :(得分:1)

您可以为旧电话添加另一个重载。

void f(int param)
{
    std::vector<type> dummy;

    f(param, dummy);   // call the modified function
}

答案 3 :(得分: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

答案 4 :(得分:0)

使用指针:

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

答案 5 :(得分:-4)

我认为它会是这样但很难看。

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