Why do I need to write “std::string” but not “std::getline()”?

后端 未结 1 915
闹比i
闹比i 2021-01-04 07:23

Consider this bit of code:

#include                                                    
#include 

int main()
{
  std::string s         


        
1条回答
  •  北海茫月
    2021-01-04 07:40

    Re the magic automatic namespace qualification.

    It's Andrew Koenig's* fault.

    He considered the problem of providing operators for user defined types. And came up with the idea of resolving the function depending on its arguments. E.g. with an argument of type defined in namespace std, the compiler looks (also) in namespace std.

    That's called either Koenig lookup or ADL, short for Argument Dependent Lookup.


    Re using namespace std;.

    For short exploratory programs you not only can, but to save work you should, do this.

    However, the standard library defines some identifiers such as distance that are very likely to collide with names you use.

    Hence, for more serious code consider whether other means of avoiding verbosity, might be better. Many programmers even maintain that you should not use using namespace std; in serious code. Some Norwegian firms have this as a coding guideline (I don't agree with so absolute a view, but you should know that it's there, and may be a majority view).

    At any rate:

        Never put a using namespace std; in the global namespace in a header

    because that makes name collisions like distance very likely for some code that includes the header.


    Why using doesn't make things accessible.

    Many programming languages, such as Java and C# and Ada and Modula-2 and UCSD Pascal, just to name some, have language support for separately compiled modules, where a module consists of functions, variables, types, constants, maybe more.

    Depending on the language a module may be called a "module" (Modula-2), a "package" (Ada, Java), a "unit" (Pascal), a "class" (Eiffel), so on.

    C++ has a much more primitive system of separate compilation, where essentially the compiler proper knows nothing about modules. The preprocessor can drag in text from "headers", which provides a way to get consistent declarations of things. And to easily get those declarations.

    But that's all, and the current primitive text inclusion system has a large number problems, most manifestly visible via various compilers' support for so called "precompiled headers" (not part of the C++ standard!).

    David Vandevoorde has worked on a module proposal for C++.

    Sadly, it wasn't ready for C++11, but maybe it will come later.

    *: In a comment David Rodriguez adds that “it is not really Andrew's fault. He only intended ADL for operators, the committee extended that to all functions”.

    0 讨论(0)
提交回复
热议问题