8

Here is a function declaration with default arguments:

void func(int a = 1,int b = 1,...,int x = 1)

How can avoid calling func(1,1,...,2) when I only want to set the x parameter and for the rest with the previous default params?

For example, just like func(paramx = 2, others = default)

JeJo
  • 30,635
  • 6
  • 49
  • 88
Y.Lex
  • 241
  • 1
  • 7
  • To acquire default arguments, you cannot provide anything after them. therefore, if you want to specify a value for `x`, you have to provide *everything* prior. – WhozCraig Aug 08 '18 at 10:14

2 Answers2

13

You can't do this as part of the natural language. C++ only allows you to default any remaining arguments, and it doesn't support named arguments at the calling site (cf. Pascal and VBA).

An alternative is to provide a suite of overloaded functions.

Else you could engineer something yourself using variadic templates.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
6

Bathsheba already mentioned the reason why you can not do that.

One solution to the problem could be packing all parameters to a struct or std::tuple(using struct would be more intuitive here) and change only the values what you want. (If you are allowed to do that)

Following is example code:

#include <iostream>

struct IntSet
{
    int a = 1; // set default values here
    int b = 1;
    int x = 1;
};

void func(const IntSet& all_in_one)
{
    // code, for instance 
    std::cout << all_in_one.a << " " << all_in_one.b << " " << all_in_one.x << std::endl;
}
int main()
{
    IntSet abx;
    func(abx);  // now you have all default values from the struct initialization

    abx.x = 2;
    func(abx); // now you have x = 2, but all other has default values

    return 0;
}

Output:

1 1 1
1 1 2
JeJo
  • 30,635
  • 6
  • 49
  • 88