Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a function take as some optional parameters in C++?

Tags:

c++

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?

like image 865
bayesNie Avatar asked Dec 17 '22 12:12

bayesNie


1 Answers

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);
}
like image 77
Vasilij Avatar answered May 10 '23 23:05

Vasilij