This is a standard / good coding practice question.
I've recently started using std::optional in my codebase. I think it's great (and verbose) for specifying an argument that's optional, so long as a reference doesn't need to be passed to that function of course.
However, it doesn't really replace a default argument in a sense that I still need to specify a value when calling the function.
Is adding std::nullopt as a default value for an std::optional argument considered a good practice? Or is it redundant / overkill, as in a sense I could have just used a default argument without std::optional in that case?
As I mentioned, I like how std::optional makes the function definition verbose, so I was interested to know about other people's approach to this.
Adding a rather crude example below. The arguments in my codebase are (small) objects but here I'm just using integers:
#include <optional>
int Foo(const int number_a,
const std::optional<int> number_b = std::nullopt,
const std::optional<int> number_c = std::nullopt) {
int result = number_a;
if (number_b.has_value()) {
result += number_b.value();
}
if (number_c.has_value()) {
result += number_c.value();
}
return result;
}
Any thoughts and suggestions are appreciated, thank you.