One line solution for unused out parameter reference
I'm not sure why having to declare an additional variable is a problem. Regardless, if you can't modify the function, make a wrapper:
void MyLimits(double& min) {
double unused;
Limits(min, unused);
}
Or you could do something funky like this:
double min;
Limits(min, *std::unique_ptr<double>(new double));
The most obvious solution would be to use pointers:
void
Limits( double* min, double* max )
{
if ( min != nullptr ) {
*min = myMin;
}
if ( max != nullptr ) {
*max = myMax;
}
}
// ...
double min;
Limits( &min, nullptr );
Alternatively, you could just define separate functions:
void Limits( double& min, double& max );
void UpperLimit( double& max );
void LowerLimit( double& min );
EDIT:
Since the orginal poster has since indicated that he cannot modify the function, he should wrap it with one which uses pointers:
void myLimits( double* min, double* max )
{
double ignore;
Limits( min == nullptr ? ignore : *min,
max == nullptr ? ignore : *max );
}
I think, with C++11 and its rvalue references, you can implement the requested one-liner. It reads as follows:
template<class T> T& make_dummy_out(T&& t) { return t; }
Then you can call your Limit function as follows:
double min;
Limits(min, make_dummy_out(double()));
This is safe, because the lifetime of the ad-hoc-created double()
will be until the end of the statement, which is after the Limits()
call has been completed.
Note, that make_dummy_out()
is basically the opposite of std::move()
: While std::move()
turns an lvalue reference explicitely into an rvalue reference, make_dummy_out()
converts an rvalue reference explicitely into an lvalue reference. Of course, you need to declare the template function only once, and then can use it to create dummy output parameters whereever you need it.
What nullable reference. So you're stuck with pointers.
void Limits(double* min, double* max)
{
if (min) *min = this->min_;
if (max) *max = this->max_;
}
int min;
Limits(&min, NULL);
I know I know, you're going to say "Pointers Bad!". Pointers are not bad, but if you really don't like it, I suggest looking into boost::optional
. Personally, I feel like this unnecessarily adds code complexity.