Should '#include' and 'using' statements be repeated in both header and implementation files (C++)?

后端 未结 5 1567
無奈伤痛
無奈伤痛 2021-02-14 20:33

I\'m fairly new to C++, but my understanding is that a #include statement will essentially just dump the contents of the #included file into the location of that statement. This

5条回答
  •  情话喂你
    2021-02-14 20:38

    A using-directive (using namespace std;) should not reside in a header unless it is contained within a function. It is bad practice. It is unlikely that every user of your header wants unqualified lookup for everything in a given namespace; the inclusion of unrelated headers can lead to unexpected ambiguity and compilation failures. Personally, I avoid the using-directive inside of functions for the same reasoning, but this is generally considered less harmful.

    A type alias (either through typedef std::string string; or using string = std::string;) should be used carefully. Type definitions have meaning, so you should never redeclare it. For example, this is an error:

    typedef int   myint;
    typedef float myint;
    

    because of conflicting types.

    A using-declaration (using std::string; or using std::memcpy;) makes a symbol accessible for unqualified name lookup. It is extremely useful when getting for argument-dependent lookup correct, which usually doesn't matter unless you're writing a library. The advice is different depending on if you are bringing in a type or a function. Think of using-declarations with types in the same manner as a type alias: It does not make sense to have multiple definitions under the same name. With functions, all you are really doing is extending overload resolution to include a few more things (although it is usually not necessary).

    // Finding multiple operator<< functions makes sense
    using std::operator<<;
    using mylib::operator<<;
    
    // Finding multiple string classes does not make sense
    using std::string;
    using mylib::string;
    

    For repeating #include, you should consider if you actually need to include the file in the header in the first place. Perhaps a forward declaration fits your needs.

提交回复
热议问题