C++ using for std and boost namespace best practice [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?
I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each and boost::bind. I used in C# and thought that using directives would rock for readability of the code and generally faster development. It would be a pain in the neck to type any namespace before C# foreach statement for example.
What are the cons and pros of using for such popular namespaces I am wondering?
Is it a best practice to include those namespaces or not?

First of all, let's make two distinctions:
1) There are using directives like using namespace std; and using declarations like using std::cout;
2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)
Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.
namespace blah
{
using namespace std; // doesn't pollute the *global* namespace, only blah
}
Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.
Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).
In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.
namespace MyLocalName
{
using namespace boost;
class X
{
// can use things from boost:: here without qualification
};
}
using MyLocalName::X; // brings X back into the global namespace
But never put using namespace boost; or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.

I am against the using namespace statements, except maybe locally in a function's body. It's not a pain at all to write the full-qualified namespace before every identifier, except if you're writing like 500 loc per day.

Related

What's the purpose of declaring "namespace std {}"?

In some piece of code, I saw this declaration without understanding the exact meaning...
namespace std {}; // why?
using namespace std;
int main(){
...
}
That's a forward declaration of a namespace. You are not allowed to 'use' a namespace before it has been declared, so the declaration is necessary if you don't have any includes that bring in any part of 'std' beforehand.
Is it actually useful or necessary... That's doubtful. If you are including anything that brings in any part of std, you don't need the forward declaration. And if you are not, you don't need that using namespace std. So it might be a bit of boilerplate code - someone who was taught to 'always write using namespace std', and writes it even if it doesn't make any sense.
There is no point. I guess that code was written by someone who didn't really know what they were doing.
You'll get access to the namespace as soon as you include something anyway, so forward declaring it here doesn't really serve any purpose.
Contrary to the answers given above, I want to demonstrate a particular case where forward-declaring a namespace can be useful.
I make heavy use of Boost.Log in my application, where I use namespace lg = boost::log; for abbreviating long statements like boost::log::core::get()->.... The alias is declared in a general header file included by all components of my software, but I don't want to have all Boost.Log includes in this file, since not all components use logging. But in order to define the alias, I need to forward-declare boost::log. So my header file contains the following lines:
// boost::log namespace "forward" declaration
namespace boost { namespace log {}}
// Alternatively (from C++17 onwards):
namespace boost::log {}
// Namespace alias for boost::log.
namespace lg = boost::log;
That way, I don't need to define the lg alias in every file, which would be error-prone and tedious (and also I don't need to include the Boost.Log in the global header, which would possibly increase build times a lot).
If boost::log doesn't tell you much, think of other nested namespaces like std::chrono that one might want to alias.

using std::<type> v.s. using std namespace [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 7 years ago.
Two ways to use the using declaration are
using std::string;
using std::vector;
or
using namespace std;
which way is better?
It depends.
If you want to inject a single name into another scope, the using-declaration is better, e.g.
namespace foolib
{
// allow vector to be used unqualified within foo,
// or used as foo::vector
using std::vector;
vector<int> vec();
template<typename T> struct Bar { T t; };
template<typename T>
void swap(Bar<T>& lhs, Bar<T>& rhs)
{
using std::swap;
// find swap by ADL, otherwise use std::swap
swap(lhs.t, rhs.t);
}
}
But sometimes you just want all names, which is what a using-directive does. That could be used locally in a function, or globally in a source file.
Putting using namespace outside a function body should only be done where you know exactly what's being included so it's safe (i.e. not in a header, where you don't know what's going to be included before or after that header) although many people still frown on this usage (read the answers at Why is "using namespace std" considered bad practice? for details):
#include <vector>
#include <iostream>
#include "foolib.h"
using namespace foo; // only AFTER all headers
Bar<int> b;
A good reason to use a using-directive is where the namespace only contains a small number of names that are kept intentionally segregated, and are designed to be used by using-directive:
#include <string>
// make user-defined literals usable without qualification,
// without bringing in everything else in namespace std.
using namespace std::string_literals;
auto s = "Hello, world!"s;
So there is no single answer that can say one is universally better than the other, they have different uses and each is better in different contexts.
Regarding the first usage of using namespace, the creator of C++, Bjarne Stroustrup, has this to say in ยง14.2.3 of The C++ Programming Language, 4th Ed (emphasis mine):
Often we like to use every name from a namespace without qualification. That can be achieved by providing a using-declaration for each name from the namespace, but that's tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use a using-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using a using-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book. [...]
Within a function, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful with using-directives in the global scope. In particular, don't place a using-directive in the global scope in a header file except in very specialized circumstances (e.g. to aid transition) because you never know where a header might be #included.
To me this seems far better advice than just insisting it is bad and should not be used.
using std::string; and using std::vector;.
Polluting the global namespace with a bunch of symbols is a bad idea. You should just use the std namespace prefix too, so you know that you're using standard library containers. Which is better than both options IMO.
If you are simply using the standard library and nothing else and never will be adding in any other libraries to your project, by all means, use using namespace std; - Whatever you feel more comfortable with in that situation. The convention of "never use using namespace std;" comes from the fact that multiple other libraries define things such as string, vector and such. It is good practice to never import the whole namespace, but it should cause no bothers in your case.

Is it ok to have "using namespace" statement in a header file? [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 8 years ago.
I have been told by many programmers that having a using namespace <x> statement in a header file is a bad idea. I have been following this advice blindly till now without understanding why is it so. Now that I am working on a very complex project with lots of namespaces. At times I find it too tempting to tell the compiler about the namespace in the beginning rather than having to type nested ::'s everytime. Example:
ALongNameSpaceName::LongerNamespaceName::BasicUtilityFunctionUsedVeryCommonly
What is the rationale behind this rule? In what scenarios can I ignore this rule?
Because header files get included by other files, you pollute the global namespace of other people who use your code. You may think a little pollution is okay, but if everybody thought that way, we would run out of good names quickly. If you really can't resist using namespace directives in your headers, then limit it to within your header. You can do that by putting the directive inside a scope. For example, if you have your own namespace block, the body of which is entirely restricted to your header file, then you can put a using directive in it without polluting the global namespace.
namespace your_namespace
{
// this directive is restricted to this namespace block
using namespace ALongNameSpaceName::LongerNamespaceName;
...
}
You can do this inside functions too without worrying about it affecting other code.
Never use using namespace in a header file. This means that anyone that imports your header will have everything from that namespace dumped into their global namespace (unbeknownst to them). This has the potential to cause unexpected name clashes, hard to find/debug errors, and angry programmers out for your blood.
Always use fully qualified names in headers. Within .cpp files, however, you can always shorten the namespace:
namespace ALongNameSpaceName::LongerNamespaceName = ShortNamespace;
ShortNameSpace::BasicUtilityFunction

Is using namespace in an anonymous namespace safe?

In "using namespace" statement inside an anonymous namespace it was asked whether the following is legal
//file.cpp
//....
namespace
{
using namespace std;
}
int a(){
cout << "bla";
}
The answer was "It is". Further, using namespace directives are generally despised even if inserted in cpp files since the scope differences between header and implementation files are not rock solid since the introduction of unity builds (https://stackoverflow.com/a/6474774/484230).
My question:
Does the anonymous namespace save me from such problems or can the using
directive still propagate file borders?
In https://stackoverflow.com/a/2577890/484230 a similar approach was proposed. Does it work for anonymous namespaces as well and is it really safe?
Of course std is a bad example but e.g. using namespace boost::assign; would be quite handy in some cpp files.
There isn't any difference between putting it in an anonymous namespace and putting it outside one. Either one produces the same effect, which is bringing the entire std namespace into your file's top-level namespace. This isn't good and it should be avoided.
As for "propogating file borders", it wouldn't do that if you put it outside the anonymous namespace either. The only time it can infect other files is if it's in a file that's #included in other files, such as headers.
My question: Does the anonymous namespace save me from such problems or can the using directive still propagate file borders ?
The only way the directive could propagate file borders is if some other file had a #include "file.cpp" preprocessor directive. That is perfectly legal, too, but whoo-ey, that stinks. Including a source file as opposed to a header is very much against standard practice.
Just because something is legal does not mean that it is good.
Pretty much the same goes for using the using to bring some other namespace into the current one. using namespace <name>; is general deemed to be bad form even in a source file.

c++ namespace best practice dilemma

I'm finding that what I've considered "best practice" for use namespace in c++ is hurting the readability of my code, and making me question how to use them well.
My program consists of a few different modules which are mostly built into libraries that the "main" application uses. Each library uses it's own namespace, and their namespaces are all "inside" a project namespace to help project against name conflicts with 3rd party code. So I end up with class names such as "myproject::logging::Logger" and "myproject::reporting::ReportType" (As made up examples).
So far so good. And in my .cpp files I have no problem. I use "using myproject::logging" at the top for example, and can cleanly refer to my Logging class. In the unlikely event of a conflict between two of my namespaces I can just explicitly say which one I want. This works well.
Header files are different though. It's considered bad practice to put using statements into header files as they will affect unrelated code that may not expect them. So I always fully qualify all the names in .hpp files. That was somewhat ugly but managable up to now so I've put up with it. But now I'm increasing using template code in my libraries which means that there is much more actual code in my .hpp files now. And having to fully qualify every name is making the code practically unreadable due to the length of type names.
I'm starting to feel that the benefits of namespaces and best practice for using them are beginning to be outweighed by the unreadablilty of the code I'm having to write. I'm starting to wonder if I would be better abandoning the use of namespaces to gain the benefit of more readable code and fixing any name conflicts if and when they appear.
An alternative is to use short, single layer namespaces so instead of "myproject::logging::Logger" I would merely have "log::Logger" which would help a lot but make the likelyhood of namespace conflicts much higher, and also have the namespaces convey less useful information.
As I've said, this only really affects code in .hpp files as I'm happily using "using namespace" in my implementation files to make this manageable, but it is becoming a problem as I look at my templated code in .hpp files now and think "eww...." which can't be good :P
Anyone got any practical advice?
Here's what I do.
In <mylibrary.h>:
namespace myproject {
namespace mylibrary
{
namespace impl
{
using namespace otherlibrary;
using namespace boost;
using namespace std;
using namespace whatever::floats::your::boat;
class myclass;
class myotherclass;
};
using impl::myclass;
using impl::myotherclass;
};
};
In the source:
#include <mylibrary.h>
using namespace myproject::mylibrary; //clean!
I have been in this situation before. It is often the case that a lot of template functions/classes in your headers are really "implementation", although by the nature of templates in C++ you are forced to put them in a header file. Thus, I just put everything in some "detail" or "implementation" namespace, where I can comfortably use "using namespace". At the end, I "drop" what people should use to the corresponding place. Like this:
namespace myproject { namespace somemodule {
namespace _implementation {
using namespace myproject::othermodule;
using namespace myproject::yetanothermodule;
template <...>
class some_internal_metafunction{
...
};
template <...>
class stuff_people_should_use_outside {
...
};
} // namespace implementation
using stuff_people_should_use_outside ;
}} // namespace myproject::somemodule
This approach might enlarge a bit the names on your compiler reports, though.
Alternatively, you can give up the modules namespaces. But it might not be a good idea for an extremely large project.
Personally? I'd get rid of the "myproject" part. What is the chance that your library will use the exact same namespace name as another and have a symbol defined with the same name as another?
Also, I would suggest shorter names for namespaces you expect to be used in headers.
My experience have been that it is much more convenient to have one namespace for all your code for the reasons you mentioned in your original post. This namespace protects your identifiers from clashing with identifiers from 3rd-party libraries. Your namespace is your dominion and it is easy to keep it name-conflict-free.
I use the following to get rid of enormous amounts of std:: in header file:
// mylibrary.h
namespace myproject {
namespace mylibrary {
namespace impl {
using namespace std;
namespace stripped_std {
// Here goes normal structure of your program:
// classes, nested namespaces etc.
class myclass;
namespace my_inner_namespace {
...
}
} // namespace stripped_std
} // namespace impl
using namespace impl::stripped_std;
} // namespace mylibrary
} namespace myproject
// Usage in .cpp file
#include <mylibrary.h>
using namespace myproject::mylibrary;
It is similar to what was suggested by n.m., but with a modification:
there is one more auxiliary namespace stripped_std.
The overall effect is that line using namespace myproject::mylibrary; allows you to refer to the inner namespace structure, and at the same time it does not bring namespace std into library user's scope.
It's a pity though that the following syntax
using namespace std {
...
}
is not valid in C++ at the time when this post is written.
If your project isn't very very very huge (I mean, very huge), using only myproject should be sufficent. If you really want to divide your project into parts, you can use more generalized namespaces. For example, if I was building a game engine, I would go for namespaces like MyEngine::Core, MyEngine::Renderer, MyEngine::Input, MyEngine::Sound etc.