Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 782
Y.Lex Avatar asked Aug 08 '18 10:08

Y.Lex


2 Answers

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.

like image 74
Bathsheba Avatar answered Oct 19 '22 03:10

Bathsheba


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
like image 23
JeJo Avatar answered Oct 19 '22 04:10

JeJo