Using C++ Namespaces Safely

Namespaces are a powerful feature in C++ but sometimes they may be cumbersome. If you use the Standard Template Library (STL) a lot you may tire of typing std:: every time you need an identifier from the STL. 

int main() {
    std::string s = "Everybody everywhere!";
    std::cout << "Hello " << s << std::endl;
}

Many people will add using namespace to make typing a bit easier: 

using namespace std;

int main() {
    string s = "Everybody everywhere!";
    cout << "Hello " << s << endl;
}

The problem with using namespace std; is that it imports every identifier from the std namespace into your code. This unnecessarily pollutes your namespace and can easily create collisions. The std namespace contains a lot of identifiers. 

C++ provides a simple alternative which nicely solves both problems. There’s another version of the using statement that specifies a single name to import, without importing the entire std namespace. 

using std::cout, std::endl;
using std::string;

int main() {
    string s = "Everybody Everywhere!";
    cout << "Hello, " << s << endl;
}

In C++17 and later, you may use a list of names on one line, as in using std::cout, std::endl; above. Try to keep the list short, and the names related, to improve readability.

You can use this version of using for each of the identifiers you want to import. This provides the same convenience, while keeping your namespace clean and uncluttered. 

Share This
      

Desk: A large wastebasket with drawers, computer, and phone.

.

The lawyers made me say it: Some links may be affiliate links and I may be compensated if you make a purchase after clicking on them.