I'm having a problem with optional function parameter in C++
What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar
.
I've tried such a code:
void foo(double &bar, double &foobar = NULL)
{
bar = 100;
foobar = 150;
}
int main()
{
double mBar(0),mFoobar(0);
foo(mBar,mFoobar); // (1)
std::cout << mBar << mFoobar;
mBar = 0;
mFoobar = 0;
foo(mBar); // (2)
std::cout << mBar << mFoobar;
return 0;
}
but this line doesn't compile
void foo(double &bar, double &foobar = NULL)
with message :
error: default argument for 'double& foobar' has type 'int'
Is it possible to solve it without function overloading?
*const
pointer. It's an indirection, just like a reference - but with nullability/testability. Why complicate things with dummy variables, the bloat of Boost, etc - when the language provides a core features that fits the bill precisely as far as I can tell? – Dumbstruck