1

I am new to c++ and trying to learn how to use the optional parameters in functions.

Right now I know that you can make a function with optional parameters like this:

void X_plus_Y(int x=10, y=20) {return x + y;}

int main() {

  X_plus_Y(); // returns 30
  X_plus_Y(20); // set x to 20 so return 40
  X_plus_Y(20, 30); // x=20, y=30: return 50
  return 0;
}

But I've searched the internet and didn't find any way to pass optional arguments like this:

X_plus_Y(y=30); // to set only the y to 30 and return 40

Is there a way or a "hack" to achieve this result?

4
  • 1
    boost.org/doc/libs/1_62_0/libs/parameter/doc/html/index.html is your best bet Commented May 5, 2021 at 9:39
  • 2
    Look at named parameters. Commented May 5, 2021 at 9:40
  • @Jarod42 Holy standard. Commented May 5, 2021 at 9:50
  • pedantry: they are not optional parameters; you can just omit them and get the default values, but they always exist and have values. best not to confuse with std::optional, etc. Commented May 5, 2021 at 10:09

1 Answer 1

3

Named parameters are not in the language. So X_plus_Y(y=30); doesn't mean anything. The closest you can get is with the following: (works with clang 11 and GCC 10.3)

#include <iostream>

struct Args_f
{
        int x = 1;
        int y = 2;
};

int f(Args_f args)
{
        return args.x + args.y;
}

int main()
{
        std::cout << f({ .x = 1}) << '\n'; // prints 3
        std::cout << f({ .y = 2}) << '\n'; // prints 3
        std::cout << f({ .x = 1, .y = 2 }) << std::endl; // prints 3
}

Check https://pdimov.github.io/blog/2020/09/07/named-parameters-in-c20/ for an in-depth explanation.

Sign up to request clarification or add additional context in comments.

1 Comment

As comment links show, we can have closest syntax. But that way is simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.