3

I need to make an optional argument with a default value in my function. Currently the signature looks something like this:

void func(int a, std::optional<int> b = 10)

and the function behaves in the following way:

func(15, 5); // works
func(15);    // works 

The question is: If I remove the explicit initialization for the optional argument, like this:

void func(int a, std::optional<int> b)

Then It seems like the signature of the function changes

func(15, 5); // works
func(15);    // fails 

Which makes me very confused about the purpose of the std::optional in the first place. What is it good for if not for creating optional arguments?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
nikolaevra
  • 369
  • 2
  • 9
  • 1
    `std::optional` is a class just like any other so it must be initialized. The only way you can omit an argument is when one has a default argument. – David G Nov 14 '18 at 00:38
  • It does not make much sense to have an `optional` with a default value that is not empty as it would only confuse people. – Phil1970 Nov 14 '18 at 02:51

3 Answers3

4

What is it good for if not for creating optional arguments?

std::optional is not supposed to be used for optional argument what you expect; which requires default argument as your 1st code sample showed, std::optional won't change the language syntax.

The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.

You can used it like

void func(int a, std::optional<int> b = std::nullopt) {
    if (b) {
        // if b contains a value
        ...
    } else {
        ...
    }
}

then

func(15, 5); // b will contain a value (i.e. `5`)
func(15);    // b doesn't contain a value
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thank you, makes perfect sense to me. Found it really hard to get to the bottom of this from just cpp docs, so had to ask here. – nikolaevra Nov 14 '18 at 01:15
1

std::optional<int> is still a concrete type despite being "optional" so, unless you have a default value for it in your function specification, you need to supply one.

You seem to be conflating the two definitions of optional here:

  • the concrete type allowing you to store an object or lack thereof; and
  • the optionality (if that's even a real word) of function arguments.

They are not the same thing.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

Another use: optional return values:

// throws if cannot parse
auto parse_int(const std::string& s) -> int;

// returns std::nullopt if it cannot parse
auto try_parse_int(const std::string& s) -> std::optional<int>
bolov
  • 72,283
  • 15
  • 145
  • 224