PTorPro
PTorPro

Reputation: 73

Passing defaulted/'optional' parameters to C++ functions by name

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?

Upvotes: 1

Views: 88

Answers (1)

pablo-carbonell
pablo-carbonell

Reputation: 46

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.

Upvotes: 3

Related Questions