Faking keyword arguments to functions in C++
5 points by raymii
5 points by raymii
I was surprised more people had not adopted this strategy - it's functionally how you do it in JS as well, though obviously more concisely in JS as you don't need to explicitly create the struct.
It would be nice if you could do this more cleanly in C/C++ (something like void foo(struct { .... } args) but alas you cannot :(
C++ didn’t get designated initialiser lists until C++20 (though most compilers got it as an extension earlier, for C compatibility). And, unlike C, the fields must be initialised in order.
I’ve used this style for a while: optional arguments are passed via a struct that has default values for most things. It’s quite nice because you can add new optional things with default values and retain source compatibility. You can also retain binary compatibility if you create the new arguments structure as new type (can be a subclass of the old one) and add a new overload, then make the old one just forward to the new one copying the arguments to the extended type.
It has been mentioned already, but I wanted to leave a relevant source :)
https://en.cppreference.com/cpp/language/aggregate_initialization
This article is entirely about using aggregate initializers, the problem is just that you have to make a distinct declaration of the argument list - e.g. you cannot just have an inline single context decl of the type.
I thought that C++ is not really a superset or subset of C, so it not having named params makes no difference.
If it's any consolation, php does have named params ;)