Reputation: 3181
I'm having a scenario where I need to add a vector as an input/output [reference]parameter to existing legacy code. And in order to avoid any errors, I need to make it a default parameter.
Could someone please suggest how to add a vector as a default parameter to a method. I'm actually dubious if this is possible. Also, if this is possible, with what vallue should the vector be intialized with?
Upvotes: 5
Views: 4377
Reputation: 361612
If the default parameter has to be non-const reference type then you can do this:
//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);
}
If the default parameter hasn't to be non-const reference then you can do this:
void f(std::vector<int> v = std::vector<int>()); //non-reference
void f(const std::vector<int> & v = std::vector<int>()); //const reference
Upvotes: 0
Reputation: 6231
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, which explicitly says that vector
is an option in/out parameter, is:
void foo(double parameter, std::vector<int>* vector = 0);
Yes, a raw pointer -- we're not taking ownership of it, so smart pointers are not really needed.
Upvotes: 5
Reputation: 27684
I think it would be like this but it is ugly.
void SomeFunc(int oldParams,const vector<int>& v = vector<int>())
{
vector<int>& vp = const_cast<vector<int>& >(v);
..
..
}
Upvotes: -4
Reputation: 146968
You can't do that, because a mutable lvalue reference will not bind to an rvalue. Either you use const
and give up the out part of the param, so you can assign it a default value, or you use a mutable lvalue reference and force the caller to pass something in.
Edit: Or you can write an overload- I hadn't considered that. It's not doable in a single signature, at least.
Upvotes: 3
Reputation: 92301
You can add another overload for the legacy calls.
void f(int param)
{
std::vector<type> dummy;
f(param, dummy); // call the modified function
}
Upvotes: 1
Reputation: 56976
Use a pointer:
void foo(legacy_parameters, std::vector<int>* pv = 0);
Upvotes: 0