How to set the default value for a vector in a method

I have a scenario where I need to add a vector as an input / output [link] parameter to existing legacy code. And to avoid errors, I need to make this a default parameter.

Can someone suggest how to add a vector as the default parameter for a method. I really doubt if this is possible. In addition, if possible, with which vector should the vector c be integrated?

+5
source share
6 answers

I suggest overloading the method:

void foo(double otherParameter);
void foo(double otherParameter, std::vector<int>& vector);

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

An alternative design that explicitly states what vectorthe / out option parameter is is:

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

, - , .

+5

, lvalue rvalue. const, , lvalue -.

: - . , .

+3

.

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

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

, :

//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);
}

, :

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

Use a pointer:

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

I think it will be so, but it is ugly.

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

All Articles