I have a function that takes 3 determined parameters and one additional parameter.
In Matlab, I can use nargin < 4 to distinguish the case with the addtional parameter and that without the addtional parameter.
How can I implement a function in C++ imitating this behavior?
I found parameter pack / variadic parameter may be helpful, but I have no idea how to use it.
Can someone shed some info to me?
You can use std::optional
. In the function declaration, assign the default value of std::nullopt
to your optional argument. This is a special value designed to indicate that std::optional
doesn't contain any value. Thus, you'll be able to call your function with 3 or 4 parameters.
void function(int a, int b, int c, std::optional<int> d = std::nullopt) {
// check if d has value (there is a special bool conversion in std::optional)
if (d) {
int temp = d.value();
}
}
int main() {
function(0,1,2);
function(0,1,2,3);
}
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