I was looking at the google coding guide [here] and they do not recommend that o
ID: 655572 • Letter: I
Question
I was looking at the google coding guide [here] and they do not recommend that one use the using namespace ornamespace:function` - if I did not misinterpret it.
Does this apply to std as well? cout<< does not work without it. This book, recommends the same. So how do I go about using cout<< without using namespace std; or std::cout<< ?
What is the recommended way? std::cout<<? Most c++ text books teach beginners with using namespace std; are they propagating poor coding practice?
Explanation / Answer
As I read the Google standard, you cannot use the using namespace foo; directive anywhere. This directive brings in everything declared in the namespace and is a common cause of collisions and unexpected behavior. Others have cited a very common one: you have your own max or min method somewhere and it collides in a src file where someone includes a header with your method and then says using namespace std;
In certain places, it is permitted to have a using declaration, which is of the form using ::foo::bar;
People like to put using directives in their code because it saves a lot of typing, but it comes with risk. If you have a file with a lot of cout statements, I can understand not wanting to have to type std::cout a hundred times, but you can simply say using ::std::cout. I treat these like variable declarations: scope them where they are needed. If one function in a file of 10 needs to write output, don't declare the cout way at the top, put it in that function that is doing the actual output.
#include <ostream>
//using namespace std; // NO!
//using ::std::cout; // less bad than using namespace, but I prefer to scope it
int main(int argc, char** argv)
{
int rc = do_some_stuff(argc, argv);
using ::std::endl;
if (rc) { // print the success report
using ::std::cout;
cout << "The test run completed. The return code was " << rc << '.' << endl;
} else {
using ::std::cerr;
cerr << "Unable to complete the test run." << endl;
}
return 0 == rc;
}
That's a little extreme with just a couple of lines doing output, but you get the idea.
Another thing one can do is alias or typedef to minimize the typing. I don't find std::whatever to be that bad, but we have a huge set of source with several dozen modules and sometimes we have to write code like console_gui::command_window::append("text"). That gets tedious after a while and causes a lot of long lines. I am all for something like
typedef console_gui::command_window cw;
cw::append("text");
as long as the aliases are done in a local scope and keep enough context to make the code readable.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.