Is there a simple way to call a function with default arguments? [duplicate]
Asked Answered
O

2

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)

Obliquity answered 8/8, 2018 at 10:11 Comment(1)
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.Munitions
B
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.

Beauty answered 8/8, 2018 at 10:14 Comment(0)
M
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
Mood answered 8/8, 2018 at 10:29 Comment(1)
C++20: func({.x = 2}); :)Semifinalist

© 2022 - 2024 — McMap. All rights reserved.