10 ms·
How C++ Resolves a Function Call
- mkoubaa 6y agoI usually try to get away with reading as little of the manual as possible until I absolutely have to. Articles like this really help cavemen like me because this is leaps and bounds better than reading the actual c++ standard!
- jeffbee 6y agoC++ is really the one language where I suggest reading the manual, repeatedly. Sometimes I go and read the docs at cppreference for practically every expression I write.
- WalterBright 6y agoI'd be careful. cppreference.com is a rewrite of the Standard, likely due to copyright issues. This means errors creep in.
- MauranKilom 6y agoI'd say it's rather an attempt at having some kind of actual user manual. It's not going to be as precise (or authoritive) as the standard, but instead the focus is on being more digestible for users.
- ahartmetz 6y agoThe examples, specifically, are extremely helpful!
- logicchop 6y agocppreference.com is by far the best resource for the language and the standard library. It is also well organized and easy to navigate. "errors creep in" is a well-taken complaint about life in general, not cppreference.
- WalterBright 6y agoI implemented a printf format checker for D, which checks that the argument types are compatible with the format specifiers. (This is really a nice feature, I should have done it long ago.) To be successful, it had to correctly deal with every nuance of the printf spec. cppreference got a couple of these incorrect wrt to modifiers. Not something a routine user would notice, but a pedantic one would. (Sorry, I don't remember exactly what the mistakes were.) I still use cppreference because it is so dang convenient. But I don't rely on it when perfection is required. It's really too bad that copyright forces everyone writing a manual to rewrite & rephrase things. I wish the C++ Standard was online. One online reference I dearly like is https://www.felixcloutier.com/x86/index.html https://www.felixcloutier.com/x86/index.html which has saved me so much time. But it was created by scanning the actual reference manuals, so barring scanning errors, it is exactly correct. I gave up using reformulations of the CPU instruction set long ago, they had too many mistakes.
- jeffbee 6y agoYou might be interested in the EXEgesis project, which is also a machine interpretation of x86 documentation, but which includes several patches for unfixed errata therein. https://github.com/google/EXEgesis https://github.com/google/EXEgesis
- mhh__ 6y agoIf the CPUs have bugs in 'em the manual definitely does unfortunately.
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- tlb 6y agoIt's curious how the C++ standard is written with a bunch of rules, rather than an algorithm. The algorithmic version in the article is much clearer to programmers. You'd think the C++ standards committee would write the standard for programmers instead of for -- I don't even know who it's for. Bureaucrats? Tax lawyers? SF Zoning regulation enforcers?
- b20000 6y agoit's OK if you don't get it
- lionkor 6y agoit literally is OK if you dont, because its not written for C++ programmers, its written for compiler people, and, frankly, those are witches.
- WalterBright 6y ago> those are witches Ahem, warlocks. Be careful or I'll turn you into a newt.
- bregma 6y agoWe're not here to judge all compiler implementors on how they self-identify. In most non-Western cultures [0] both "witch" and "compiler writer" are gender-neutral terms for those who dabble in the mysteries of the dark arts. Perhaps a better, less gender-ambiguous term would be "sourcerer" indicating someone who deals in the miracles of transforming source code. [0] https://www.britannica.com/topic/witchcraft/Witchcraft-in-Africa-and-the-world https://www.britannica.com/topic/witchcraft/Witchcraft-in-Af...
- sesuximo 6y agoI think most standard readers are compiler writers.
- 6y ago
- WalterBright 6y agoI was able to use my experience implementing C++ name lookup rules to make a less complex one for D: There's no notion of a "primary" template. Templates are looked up like functions are. C++ has rather complex function overloading rules that differ substantially from template overloading rules. The former is a hierarchical list of rules, the latter is based on partial ordering. D uses partial ordering for both. D doesn't need argument dependent lookup, because it has modules. D lookup sees all the declarations in a module at once, not just ones prior to the point of use. The end result works pretty much the same, and hardly anyone notices the difference. Except for that last point - in C and C++, the order of declarations is inverted. The private functions come first, the public ones last, because lookup is dependent on the lexical order. D code is written with the public ones first, private ones last.
- dgellow 6y agoD is really underappreciated.
- yvdriess 6y agoDid you ever feel the itch to add a 'trait' to access and manipulate the partial ordering set? Something like CLOS' method combinators or call-next-method (to call the next most specific function).
- WalterBright 6y agoNo, I never thought of it. I have no idea what purpose calling the next most specific function would serve. Besides, there are ways to call specific functions other than the best match - like casting the arguments to types that make it an exact match with the desired function. Despite the power of D's overload mechanism, my advice is to use overloading modestly, not cleverly. You've written your best code when a newbie looks at it and remarks "pshaw, I could have written this! Why does Walter make so much money?"
- bmn__ 6y ago> I have no idea what purpose calling the next most specific function would serve. This is a replacement for calling the superclass, but it uses C3 method resolution order.
- CyberRabbi 6y agoAdvanced function resolution technology is one of the main reasons I use C++. The combination of being statically typed yet allowing users to create elaborate function dispatch hierarchies is unmatched.
- divs1210 6y agoIt's not unmatched, though? Never heard of Julia or Rust?
- saagarjha 6y agoThere's not need to be dismissive. C++ has a somewhat strange position in that it is statically typed but the mechanism of type resolution is fairly loose. This, coupled with SFINAE, allows for concise declarations of things that would take much more work in other languages (or not be possible). If you've ever written a generic constraint in Rust specifying every arithmetic operation that you use in the function body, then you'll know what I mean.
- CyberRabbi 6y agoYes transparent dispatch into templated functions (chosen via SFINAE) may not be everyone’s cup of tea but I prefer it to a separate macro language. No exclamation marks, looks like a normal function and later can be reimplemented as a normal function.
- simiones 6y agoThe huge problem with SFINAE and most template techniques is that the semantics of the operation are completely different from the intention, and this always shows in error messages for any small mistake, even most of the ones your users make. Concepts were supposed to help, but based on what I've heard, they sometimes make the error messages even worse, so I'm not sure.
- pansa2 6y agoJulia is dynamically typed.
- wyldfire 6y ago> , it should at least be possible to implicitly convert each argument to its corresponding parameter type. Oh no! You just got burned (maybe). Make sure you turn on your compiler's warnings to find bogus-but-legal implicit conversions.
- mshockwave 6y agoWe need more articles like this on other aspects of C++
- dgellow 6y agohttps://www.reddit.com/r/cpp https://www.reddit.com/r/cpp is a place where you can find some good content (unfortunately, not consistently). I would also be happy to read more articles like this one. I personally don't use C++ other than for small side projects, but it's a world fascinating to explore.
- arcticbull 6y agoIf skynet ever happens, it'll be a self-aware C++ compiler, mark my words. That's why it hated us so much in the Terminator documentaries.
- dgellow 6y agoToo late, Skynet already happened in the form of Bitcoin.
- KineticLensman 6y ago> it'll be a self-aware C++ compiler, mark my words. That's why it hated us so much in the Terminator documentaries Sorry, but no. Terminators hate us because they were programmed in a mix of COBOL and 6502 assembler [0] [0] https://www.theterminatorfans.com/the-terminator-vision-hud-source-code-explained/ https://www.theterminatorfans.com/the-terminator-vision-hud-...
- px43 6y agoIf Skynet emerges as a C++ compiler, it'll be trivially confused and obliterated by the first freshman CS student that it comes in contact with.
- rapsacnz 6y agoAnd this is one of the reasons why C++ is a mess.
- unnouinceput 6y agoOr use a good IDE which would have something like "right click -> jump to declaration" and it will show you what/where the function is implemented. Or at least that's what I do to keep up my productivity instead of wondering at the marvels of overloading / namespaces that export same function names.
- masterofmisc 6y agoHuh... So your saying "right click -> jump to declaration" uses the compiler to resolve all the candidate functions to determine the function that would of been chosen at compile time? ..and then take you to that function? I thought it just took you to the 1st occurrence of the function it found. If so, that's interesting.
- MauranKilom 6y agoReally depends on your IDE. As an example, Visual Studio ships Microsoft's CPP compiler (MSVC [0]), but uses a completely different compiler frontend (namely EDG [1]) for IntelliSense. In a way, it does use a compiler to resolve the candidate functions, but it doesn't go through all the compilation stages. And it's not even the same compiler as when you hit compile :) [0]: https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B [1]: https://www.edg.com/ https://www.edg.com/
- masterofmisc 6y agoAhh that's interesting to know. Thanks for the info.
- nestorD 6y agoThe complexity of the language makes it hard to do even for state-of-the-art IDEs. I have had up to date versions of CLion suggest a dozen potential declarations in some hairy codebases...
- gjulianm 6y agoThe point of the article is not to manually resolve all function calls. Understanding the algorithm allows you to see why a compiler sometimes doesn't choose the function you want and fix it.
- rjzzleep 6y agoThis is a good article in terms of context, but I found it much easier to understand how C++ does class functions when I first saw this in a disassembly output. I guess I'm a more visual learner that has a fairly hard time following a lot of text.
- gmueckl 6y agoThis article doesn't touch codegen. It is merely about the algorithm by which the compiler disambiguates e.g. which function or method named foo you meant to call when you write e.g. foo(1, 3) vs. x::foo("bar").
- arunc 6y agoUnrelated to C++, but the diagrams (svg) looks nice. Are these created from text format or via some diagram tool, because if it is from text, it's nice to use in architecture diagram (asciidoc/markdown), etc and version control with git. PlantUML works well for sequence diagrams, but for the rest, the output is not pleasing to look at.
- SubjectToChange 6y agoThe author responded to this question on reddit: https://www.reddit.com/r/cpp/comments/m5jpwz/_/gr10ysr https://www.reddit.com/r/cpp/comments/m5jpwz/_/gr10ysr
- ktpsns 6y agoWow, this website is one of the first ones in the wild I see which seamlessly integrate SVG into the text flow to produce a single look. Amazing work!
- qalmakka 6y agoWhat has always fascinated me of C++ is how incredibly complex, yet wild, it is. You can do basically everything, you can create horrible monsters and discover beautiful patterns backed by strong type safety. It might not be for everyone, but yet I find it can be as rewarding as it is frustrating. You always learn something, and you can always dig yourself out of any hole, it just requires effort and skill.
- kazinator 6y agoC++ resolves certain kinds of tricky function calls via a remote procedure call that sends an SMTP mail to the ISO committee, and waits for a reply. (It's compile time though, no biggie.)
- einpoklum 6y agoRule of thumb: If your code has ambiguities that make you reach for the details of name resolution rules, or depend on some finer point within them, then - seriously consider differentiating the names. In the example in the article - I would go to some trouble to avoid having both: namespace galaxy { void blast(Asteroid* ast, float force); } and template <typename T> void blast(T* obj, float force); either blasting asteroids happens in the context of galaxies, or it doesn't. If there are _different kinds_ of blasting of asteroids - very well, make that explicit. Also, bool blast(Target target); would be somewhat confusing, since people may expect `blast()` to not return anything and will neglect to check the returned value. And wouldn't it make more sense to just have a default amount of force for the blast? ... again, if it's a different kind of blast, don't name both functions the same. PS: * "Better is a good name than fine oil" (that's a biblical proverb). * Don't be a smart-ass when naming! You'll smile for a second, others will cry for years. * Don't be stingy with a few more characters in your name - we can handle it.