Reputation: 10606
Is there a compact way of skipping an out-parameter from a function call by passing some dummy?
In the example below I would like to write something like calc_multiples(myNum, NULL, myNumTimes3)
, because I do not need the second parameter and hence do not want to define a variable for that.
In python one would use _
for that..
#include <iostream>
/**
* Calculates multiples of number
*
* @param[in] t1 number to multiply
* @param[out] t2 multiplied by 2
* @param[out] t2 multiplied by 3
*/
void calc_multiples(const int t1, int &t2, int &t3)
{
t2 = 2*t1;
t3 = 3*t1;
return;
}
int main()
{
int myNum = 7;
int myNumTimes2; // I want to avoid this line
int myNumTimes3;
calc_multiples(myNum, myNumTimes2, myNumTimes3);
std::cout << "my number times 3: " << myNumTimes3;
return 0;
}
Upvotes: 3
Views: 938
Reputation: 96246
There's no direct alternative to Python's _
.
The function should be rewritten to take pointers instead of references, and it should check that the pointers are not null before writing to them.
Then you would pass nullptr
to the parameters you want to skip.
Comment by the author of the question (Markus Dutschke)
Code would look like this
#include <iostream>
/**
* Calculates multiples of number
*
* THIS IS JUST FOR DEMONSTRATION.
* OF COURSE ONE WOULD USE DEFAULT ARGUMENTS IN THIS CASE.
*
* @param[in] t1 number to multiply
* @param[out] t1 multiplied by 2 (optional argument)
* @param[out] t1 multiplied by 3 (mandatory argument)
*/
void calc_multiples(const int t1, int *t2, int &t3)
{
if (t2 != nullptr)
{
*t2 = 2 * t1;
}
t3 = 3 * t1;
return;
}
int main()
{
int myNum = 7;
int myNumTimes2; // I want to avoid this line
int myNumTimes3;
calc_multiples(myNum, nullptr, myNumTimes3);
std::cout << "my number times 3: " << myNumTimes3;
return 0;
}
Upvotes: 1
Reputation: 596307
You can simply define another function that omits the undesired parameter:
#include <iostream>
/**
* Calculates multiples of number
*
* @param[in] t1 number to multiply
* @param[out] t2 multiplied by 2
* @param[out] t2 multiplied by 3
*/
void calc_multiples(const int t1, int &t2, int &t3)
{
t2 = 2*t1;
t3 = 3*t1;
return;
}
void calc_multipleOf3(const int t1, int &t3)
{
int ignored;
calc_multiples(t1, ignored, t3);
}
int main()
{
int myNum = 7;
int myNumTimes3;
calc_multipleOf3(myNum, myNumTimes3)
std::cout << "my number times 3: " << myNumTimes3;
return 0;
}
Alternatively:
#include <iostream>
/**
* Calculates multiples of number
*
* @param[in] t1 number to multiply
* @param[out] t2 multiplied by 2
* @param[out] t2 multiplied by 3
*/
void calc_multiples(const int t1, int &t2, int &t3)
{
t2 = 2*t1;
t3 = 3*t1;
return;
}
int main()
{
int myNum = 7;
int myNumTimes3;
auto calc_multipleOf3 = [](const int t1, int &t3) {
int ignored;
calc_multiples(t1, ignored, t3);
};
calc_multipleOf3(myNum, myNumTimes3)
std::cout << "my number times 3: " << myNumTimes3;
return 0;
}
Upvotes: 3