How to set default for a vector in a method
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 possibl开发者_运维技巧e. Also, if this is possible, with what vallue should the vector be intialized with?
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.
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.
You can add another overload for the legacy calls.
void f(int param)
{
std::vector<type> dummy;
f(param, dummy); // call the modified function
}
Use a pointer:
void foo(legacy_parameters, std::vector<int>* pv = 0);
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
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);
..
..
}
精彩评论