List of C++ name resolution (and overloading) rules

岁酱吖の 提交于 2019-11-26 18:00:54

问题


Where I can find a list of the rules that a C++ compliant compiler must apply in order to perform names resolution (including overloading)?

I'd like something like a natural-language algorithm or flow chart.

C++ standard of course has this set of rules but it is build up as new language statements are introduced and the result it's pretty hard to remember.

To make a long story short, I'd like to know the complete and detailed answer to the question "What compiler do when it see the name 'A'?"

I know C++ is all "We do this when X but not Y if Z holds" so, I'm asking whether it is possible to make it more linear.

EDIT: I'm working on a draft of this topic, something that may be improved collectively once posted. However i'm very busy this days and it may take time to have something publicable. If someone interested i'll promote the "personal note on a raw txt file" to something better and post it.


回答1:


Well, in broad strokes:

  • If the name is preceded by ::, as in ::A or X::A, then use qualified name lookup. First look up X, if it exists (if not use the global namespace) then look inside it for A. If X is a class, and A is not a direct member, then look in all the direct bases of X. If A is found in more than one base, fail.

  • Otherwise, if the name is used as a function call such as A( X ), use argument-dependent lookup. This is the hard part. Look for A in the namespace the type of X was declared in, in the friends of X, and if X is a template instantiation, likewise for all the arguments involved. Scopes associated only by typedef do not apply. Do this in addition to unqualified lookup.

  • Start with unqualified lookup if argument-dependent lookup doesn't apply. This is the usual way variables are found. Start at the current scope and work outwards until the name is found. Note that this respects using namespace directives, which the other two cases do not.

Simply glancing at the Standard will reveal many exceptions and gotchas. For example, unqualified lookup is used to determine whether the name is used as a function call, as opposed to a cast-expression, before ADL is used to generate a list of potential overloads. Unqualified lookup doesn't look for objects in enclosing scopes of nested of local classes, because such objects might not exist at the time of reference.

Apply common sense, and ask more specific questions when (as often it does) intuition fails.



来源:https://stackoverflow.com/questions/7374588/list-of-c-name-resolution-and-overloading-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!