0

Say I have a function like the following in c++,

int sum(int x = 0, int y = 0) {
    return x + y;
}

I can use the default value of y by calling the function like sum(3) which would then return 3. Is it possible to use the default value of x, and not y? I know I can call the function with the default value of x explicitly like sum(0,4), but is there a way to call the function like sum(y = 4) which would then use the default value of x?

  • There are some libraries which allow named parameter to have your expected syntax or similar. You might look that article [Named Arguments in C++](https://www.fluentcpp.com/2018/12/14/named-arguments-cpp/). – Jarod42 Nov 03 '21 at 11:44

1 Answers1

5

No, there is no way. A possible workaround is to use std::optional:

int sum(std::optional<int> x = {}, std::optional<int> y = {}) {
    return x.value_or(0) + y.value_or(0);
}

Then you can use {} or std::nullopt to use the default value: sum({}, 4).


Note that if you pass {} to an int parameter (as opposed to std::optional<int>), it will always pass zero, regardless of what the default argument is.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207