8 ms·
Named Parameters in C++20
- amboo7 6y agoBravo, it's time
- jleahy 6y agoUnfortunately in many cases this will cause all of the parameters to be passed via the stack rather than in registers. It’s a meaningful penalty for the kind of people who would willingly select c++ as a language today (rather than, say, python or java).
- ducaale 6y agoWouldn't be possible for the compiler to optimize it away?
- flohofwoe 6y agoOnly if the function is inlined, at least it seems that way from experimenting on godbolt.org.
- nikki93 6y agohttps://godbolt.org/z/11931W https://godbolt.org/z/11931W Here's an example where it happens even when not inlining.
- flohofwoe 6y agoI guess that's because the struct size is below 16 bytes (see my sister comment). Adding two more ints to the struct places the entire content on the stack.
- bitwalker 6y agoI'd expect scalar replacement of aggregates (SROA) would eliminate the use of a struct like this in some cases, but there are definitely limits, especially if not compiling with LTO enabled, since optimizations across compilation units will be limited. Honestly doesn't seem worth the cost.
- nikki93 6y agoUsing registers to pass structs is an ABI thing and doesn't need LTO, it happens during compilation (see godbolt.org links on the rest of this thread).
- flohofwoe 6y agoFrom my experience with C99: if the struct size is 16 bytes or less, the values will be packed into registers. But true as soon as the struct grows bigger, the entire content will be passed on the stack. IMHO this sort of named arguments "easter egg" is fine for big "option bag structs" passed to functions that are not performance critical (or for small struct <= 16 bytes). For other cases, regular args are better. OTH it seems like passing normal args also spills over into the stack very soon (only 4 registers used?): https://www.godbolt.org/z/Mz9MTG https://www.godbolt.org/z/Mz9MTG The main difference seems to be that normals arguments "spill over", while passing structs by value puts everything on the stack once the threshold size is passed.
- archgoon 6y agoSix arguments use registers (and rax for return). The first two in your example are in the lea instruction. Using rdi, rsi, rdx, rcx, r8, r9 and then the stack is the calling convention used on x64 linux. 32-bit (-m32 in godbolt) linux would use the stack exclusively.
- account42 6y ago> Using rdi, rsi, rdx, rcx, r8, r9 and then the stack is the calling convention used on x64 linux It's more complicated than that - floats/doubles and structs of them are put in SSE registers instead. Mixed structs are packed into integer registers (!) if they are small enough. And with C++ classes with non-trivial destructor/etc. are always passed on the stack.
- nikki93 6y agoSix of the parameters use registers here. the `lea` is putting the sum of the first two into `eax`, then the rest accumulate more adds into `eax`. Only the last 3 parameters are reading from stack memory (the `dword ptr [*]` stuff). In any case you don't get to actually see the passing at the callsite because the result `45` is inlined into `main()`. :)
- flohofwoe 6y ago
- andi999 6y agoWhy?
- dahfizz 6y agoEverything that's not a struct that you would pass as a parameter (int, pointer, char, etc) all fit in a register and there are register reserved for function parameters in the ISA. Structs with more than one field don't fit into a register.
- gumby 6y agoYou can write a trivial template that generates a parameter pack which the compiler should be able to optimize at compile time. However in my experience there are human factors problems which I posted in another comment.
- asveikau 6y agoIn c++ it also seems likely that with this approach you could invoke some pretty expensive copy constructors if some of the parameters have those.
- nikki93 6y agoIf it's a prvalue there is no copying involved. Here's an example where one of the 'parameters' has an 'expensive' copy constructor but it isn't invoked at all: https://godbolt.org/z/94ehvx https://godbolt.org/z/94ehvx However, if you use an lvalue expression then yes, the copy constructor is invoked (in `bar` here), and you can avoid that by using an xvalue expression (in `baz`, using `std::move`): https://godbolt.org/z/MnKnWM https://godbolt.org/z/MnKnWM Basically it doesn't depend on being passed through a struct as much as on the parameter itself. You'd see the same behavior if the `C` struct was passed as a regular parameter.
- moonchild 6y agoPer the sysv abi, sec. 3.2.3, parameter passing: > If the size of an object is larger than eight eightbytes, or it contains unaligned fields, it has class MEMORY > [...] > If the size of the aggregate exceeds a single eightbyte, each is classified separately. Each eightbyte gets initialized to class NO_CLASS. So that only happens if the whole structure is bigger than 64 bytes. Otherwise everything gets passed in registers like normal.
- account42 6y agoOnly 16 bytes are passed in registers except for float types: > If the size of the aggregate exceeds two eightbytes and the first eight-byte isn’t SSE or any other eightbyte isn’t SSEUP, the whole argumentis passed in memory.
- tasubotadas 6y agoIt's a feature that I learned to use in Python and one that I consistently now miss in other languages (rust, java, typescript, javascript).
- reificator 6y agoIn ts/js passing an object is not very much effort and doesn't add much noise to reading the code.
- KarimDaghari 6y agoHonestly, In my experience named params are better than positional ones, but then again, they’re not mutually exclusive.
- deleted 6y ago[deleted]
- wk_end 6y agoIt's annoying in TS because (AFAIK?) you need to specify the type and unpack the object: function foo({arg1, arg2, arg3}:{arg1: Thing1, arg2: Thing2, arg3: Thing3) { ... }
- KarimDaghari 6y agoYou could specify the type first (instead of doing it inline) and then unpack (if you want)
- gumby 6y agoHaving programmed in languages with named parameters (Smalltalk, ObjC and Commonlisp) I’ve found them cumbersome. Also they can lead to a poor pattern which is functions/methods that take too many parameters. They also tend to make generics harder to understand as the possible parameters can vary. Of course you can make the same problem in C++ via, say, `auto multiply(int x, int y)` and `auto multiply(double x, double y, enum rounding rp = rounding::nearest)` In general they impose the verbosity (in keyboarding and reading) in the routine cases but don’t free you from having to look up the argument semantics of lesser-used functions. Side point: I used “keyboarding” because the obvious word, “typing” has a homonym which made the sentence confusing!
- rietta 6y agoI use the equivalent of named parameters in Ruby as my preferred method for a few reasons: 1. Clearly communicates the purpose of the variable 2. Means that order of parameters is not important 3. Makes the internal interface largely compatible with its JSON web service interface It's been about 10 years since I coded any Objective-C and I do agree that syntax was an oddbal.
- stephenhuey 6y agoYes, I’ve used it in Ruby and now I find myself using it a lot in Dart. Also, the Flutter widgets use it and I find it much easier to figure out which arguments to fill in with my IDE instead of always jumping over to the documentation.
- vlovich123 6y agoI found it quite useful & more natural to read in Objective-C/Swift & in those you typically are writing in an IDE that auto-completes all the names. I've also not generally found them cumbersome in Python where I code primarily in VIM without auto-completion. YMMV
- ape4 6y agoOn no! Something in C++ that can be misused ;)
- mucholove 6y agoThis is my favorite feature of Objective-C / Smalltalk. It makes everything so readable. I can come back to my code a few weeks later and I don’t really need to look up function signatures. In particular, my favorite thing about this in Objective-C is that the C functions have a different way of being called so you can easily distinguish between the differences in paradigms. I wonder what other languages force all calls to be via named parameters. Would love to have another option :)
- masklinn 6y agoSwift, kinda: named is the default but you can make parameters explicitly positional (by setting the label to _). I guess in Python you could l’ont your codebase to require keyword parameters or opt-in positionals.
- marvy 6y agoThe title is slightly click-bait-y: C++20 doesn't have default parameters. It talks about how to fake it with structs. It's a pretty convincing fake, but it has one problem: the person who wrote the function needs to have written it that way. What I wish more languages had (C++, Java, etc.) is the following: Suppose I write some function that take way too many parameters: void foo(char a, short b, long c, float d, double e){} What I want, as a caller, is for the language to let me get a struct corresponding to the argument list, something like this: foo::args whatever; whatever.e = 3.14; // fill in the rest And then add a bit of magic syntax so we can "unpack" that struct to actually call foo. (Extending this proposal to handle varargs is left as an exercise to the reader, because I have no idea.)
- spanishgum 6y agoHow about `std::make_from_tuple` for constructors or `std::apply` for functions (C++17)? It might be a bit verbose, but I think I would still prefer this over native syntax for unpacking.
- adrift 6y agoWhy would you kill your compile times like that.
- marvy 6y agoThis mostly solves the unpacking problem. Thus, there are only two problems left: 1. I need to handcraft the tuple type myself, and make sure it matches the function declaration. (In other words, I don't want to manually write tuple<char, short>. I want to write foo::arg_tuple.) 2. This provides no support for named parameters. Tuples in C++ are numbered, not named.
- thetic 6y agoThough limited, C++ does support default parameters: https://en.cppreference.com/w/cpp/language/default_arguments https://en.cppreference.com/w/cpp/language/default_arguments.
- 6y ago
- randyrand 6y agopersonally i’d just write a linter that adds names via comment open(/port/ 127)
- cma 6y agoIs there a way to have initialization fail at compile time if all members aren't included? So that if new members are added, all call sites become invalid until updated?
- atq2119 6y agoYou could probably define the arguments struct so that all its members have types without default constructors / with deleted default constructors.
- OskarS 6y agoI don't think you'd want to. One of the primary usages of this kind of thing would be like when you need to pass in some massive struct of options to some dumb API function (you know the ones!), and then you'd absolutely want default values for all the things you don't want to specify. Also, some might argue that what you're describing (call sites not becoming invalid when you update the function) is a feature, not a bug. This way, you can add options to your functions and still have everything compile like it should. I wouldn't personally argue that though, i think it leads to bad practice where functions take a bazillion options and they become horrible tech debt. I'm working in a mixed C++ and Lua codebase, and the Lua codebase is littered with functions that take, like, 9 different arguments that change the behavior of the function. When I asked one of my colleagues about this style, he said it was one of his favorite features of Lua, that you can add arguments to a function to change the behavior in certain cases but keep the original functionality (guarded with default values or if's or whatever). It's made much of the code a living nightmare! So, I guess, in the process of writing this comment I've come over to your side :) say no to adding arguments with default values!
- cma 6y agoI don't mind it for thing like pyplot where you have tons of style options hidden away like that. But I'd definitely like to be able to say this one isn't optional or implicitly default constructed (or worse uninitialized, maybe that is already precluded by any amount of brace initialization, or maybe not if the class is POD, I'll have to check). Someone suggested below deleting default constructors, you could make a template class that did that and forwarded other constructors, but I'd still like to be able to allow explicit default initialization in the ones that aren't considered optional.
- ambyjkl 6y agoThis is quite interesting, a very elegant struct hack. Dlang is working on an RFC for implementing this feature right into the language, which would probably make it the first systems language to implement this without structs. https://github.com/dlang/DIPs/blob/master/DIPs/DIP1030.md https://github.com/dlang/DIPs/blob/master/DIPs/DIP1030.md
- chiffre 6y agoAda arguably is a system programming language and it supports named parameters.
- axilmar 6y agoPersonally I'd like c++ to: a) have default parameters in any parameter position. I.e. for this to be legal: foo(int x = 0, int y, int z = 0) {} b) to allow me to invoke a function like this: foo(,) //x and z are passed as default values: c) or like this using named parameters: foo(x = 5, y = 1,)