Named arguments like in python but more limited #870
Replies: 1 comment 2 replies
-
See also #202 (comment), which links to #193 (comment):
|
Beta Was this translation helpful? Give feedback.
-
See also #202 (comment), which links to #193 (comment):
|
Beta Was this translation helpful? Give feedback.
-
For years the C++ community has been waiting for named function arguments. Other software languages, like python, support it and allow the user to write more explicit code.
Unfortunately the regular C++ can't allow it and probably won't in the next versions. there are cumbersome workaround.
Let's take for example a simple convert function:
convert : (from : double, to : double) = { ....}
I have seen so many bugs for calling functions like convert with the wrong arguments order. named arguments, like in python, solve the bug before it appears.
convert(from=0.4, to=10.7)
Python also allows a different order of the parameters, but I don't think it's possible or necessary.
While in traditional C++ argument names are not part of the signature of a function, in Cpp2 it can be part of it, at least before the conversion to cpp file. The compiler can check the names before translate it to Cpp function. the user won't be allowed to define two functions with the same argument types and different names:
convert : (from : double, to : double) = {...}
convert : (to : double, from : double) = {...} // compilation error - convert(double, double) is already declared
Here are some usages and the expected result:
convert(to=12, from=7); // compilation error for wrong names.
convert(from=2, 6); // ok or error? I'm not sure but I guess it should be allowed
convert(1,3); // I guess this should be allowed
In addition it will be nice to allow force named arguments in the function declaration:
convert : ( [[named argument]] from : double, to : double) = {...}
will force the user to write from explicitly, but not "to". for example:
convert(to=12, from=7); // compilation error for wrong names.
convert(from=2, 6); // ok!
convert(1, 3); // error - from should be named explicitly
convert(1, to=3); // error - from should be named explicitly
My suggestion for regular c++ style functions, named arguments won't be allowed at all.
As a programmer, and more over as a team leader, I have seen developers spending weeks (I'm not exaggerating) for misusing a function by replacing the order of the parameters. Named arguments, and forced named arguments, can eliminate these bugs completely and save a lot of time.
Beta Was this translation helpful? Give feedback.
All reactions