Assume this code:
#include<stdio.h>
int t(int a, int b=6, int c=7){
return b;
}
int main(){
return 0;
}
How can I call t
and only pass a and c
values and let b
as the default value?
Assume this code:
#include<stdio.h>
int t(int a, int b=6, int c=7){
return b;
}
int main(){
return 0;
}
How can I call t
and only pass a and c
values and let b
as the default value?
There is no way to do that. Arguments can only be passed in order, and therefore it is not possible to use a default argument for an argument that is before another that is passed explicitly.
You could however use an aggregate class as an argument, which combined with default member initialisers and designated initialisers (C++20) is a decent emulation of named argument passing:
struct Args {
int a;
int b = 6
int c = 7;
};
int t(const Args& args);
int main()
{
t({
.a = 42,
// b will be 6
.c = 1337,
});
}
Using designated initialiser isn't mandatory, so C++20 isn't required. It's just more concise and readable.
Depending on the structure of the program, it may make sense for t
to be a member function of the class.
This will work if you just want to overload b
. If you aim at overloading c
at the same time, then you should go with something more complex as mentioned in other answers. ;)
There is no direct way to do that in C++. Though you can chain function calls (this is very popularly used in implementing methods of classes with members as default params).
Something like this should work just fine as a workaround:
#include<iostream>
int t(int a, int b, int c) {
return b;
}
int t(int a, int c) {
return t(a, 6, c);
}
int main() {
auto x = t(1, 2); // this will call t with a = 1, b = 6, c = 2
std::cout << x; // prints 6
return 0;
}