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 th
Don't use references for optional parameters. There is no concept of reference NULL: a reference is always an alias to a particular object.
Perhaps look at boost::optional or std::experimental::optional. boost::optional
is even specialized for reference types!
void foo(double &bar, optional<double &> foobar = optional<double &>())
It is much easier to use a pointer type and setting it to NULL than setting default/optional value for a reference parameter.
void foo(double &bar,
double &foobar = const_cast<double &>(static_cast<const double &>(0.0)))
{
bar = 100;
foobar = 150;
}
You can do this crazy way:
void foo(double &bar, double &foobar = (*(new double())))
P.S. - I know its not pleasant but its the way. Also be sure not to leave memory leaks! :))
Here is another crazy way that does not result in memory leaks, which you should never use in real life, but seems to be standard compliant at first glance and compiles with Visual C++ 2008 & g++ 3.4.4 under Cygwin:
void foo(double &bar, double &foobar = (*((double*)0)))
{
bar = 100;
double* pfoobar = &foobar;
if (pfoobar != 0)
foobar = 150;
}
To reiterate: DON'T DO THIS! THERE ARE BETTER OPTIONS! OVERLOADING CAN BE YOUR FRIEND! But yeah, you can do it if you're foolish and careful. :)
The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is
static double _dummy_foobar;
void foo(double &bar, double &foobar = _dummy_foobar)