In C++, does it make sense to use a function with std::optional<T> parameter, to denote optional parameters?

Viewed 138

I know that one can implement functions with optional parameters like so:

int someFunction(int A, int B = -1) {
   if (B != -1) {
       ... // If B given then do something
   } else { 
       ... // If B not given then do something else
   }
}

However, I'd lake to take advantage of std::optional as recommended by a coworker. Here's what I'm trying to do but I'm getting errors:

int some Function(int A, std::optional<int> B) {
    if (B.has_value()) {
        ... // If B given then do something
    } else { 
        ... // If B not given then do something else
    }
}

The problem is that in the first approach, I can call the function like so someFunction(5) and C++ will realize I've opted not to use the optional parameter. But in the second aproach calling someFunction(5) in the same way will produce the error too few arguments to function call.

I want to be able to call the function without including the optional argument with the second approach, is this possible/recommended?

2 Answers

To use it in the way you intend here, I believe you'd need to specify a default value of std::nullopt:

int some Function(int A, std::optional<int> B = std::nullopt) {
    if (B.has_value()) {
        ... // If B given then do something
    } else { 
        ... // If B not given then do something else
    }
}

It doesn't really make sense; the normal solution would be an additional overload int some Function(int A).

Related