I've been trying to pass a std::vector to a function by reference with default value being an empty std::vector. The declaration of my function looks as follows:
void function( std::vector<double>& vec=std::vector<double>(0));
The definition of my function is:
void function( std::vector<double>& vec)
{
...
}
However my C++ compiler (gcc 4.6) is throwing an error here, saying:
error: default argument for parameter of type ‘std::vector&’ has type ‘std::vector’
I've seen this version of the code compile fine on a Microsoft VS 2010 compiler. And I'm wondering if this is an issue of different c++ standard interpretation between gcc and vs2010.
You can't. You can't bind a temporary to a ref-to-non-const, so you could only do this:
void function(const std::vector<double>& vec = std::vector<double>());
In your case, then, I suggest function overloading:
void function(std::vector<double>& vec)
{
// ...
}
void function()
{
std::vector<double> v;
function(v);
}
If you don't like the extra function call then you're out of luck. :)
I don't know whether C++11 rvalue refs might help here, if you have access to them.
I've seen this version of the code compile fine on a Microsoft VS 2010 compiler. And I'm wondering if this is an issue of different c++ standard interpretation between gcc and vs2010.
MSVS has a tendency to allow you to bind temporaries to refs-to-non-const, which is non-standard behaviour. GCC is correct.
You can do the following:
namespace{
auto empty_vec = std::vector<double>();
}
void function(std::vector<double>& vec=empty_vec);
then you do not have to change the signature of your function. But you have to define the variable empty_vec instead. I put it in an unnamed namespace to make it invisible from outside this translation unit.
But the drawback is (as LightnessRacesinOrbit noted below) that within this translation unit the value of empty_vec can be changed, which might break your function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With