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.
Related
I am little confused as to which one is the better way to use using C++ keyword for namespaces. Suppose that the following code is in a header file backtrace.h
#include <memory>
using my_namespace1::component1;
using my_namespace2::component2;
namespace my_application {
namespace platform_logs {
class backtrace_log {
//code that creates instances of my_namespace1::component1 and my_namespace2::component2
};
}
}
OR
#include <memory>
namespace my_application {
namespace platform_logs {
using my_namespace1::component1;
using my_namespace2::component2;
class backtrace_log {
//code that creates instances of my_namespace1::component1 and my_namespace2::component2
};
}
}
which one is better and why ?
You should always pull in symbols from other namespaces in as narrow a scope as possible (to not pollute outer namespaces) and generally, only pull in the specific symbols you need, not just the entire namespace.
In headers (that may get included by many users) you should generally refrain from the practice alltogether and instead prefer to always just use explicit namespace qualifications on types.
In a header file... the following example is evil. Never use using namespace... in the global scope of a header file. It forces a lot of unasked for symbols on the user that can cause very hard to fix problems if they clash with other headers.
#include <memory>
using my_namespace1::component1;
using my_namespace2::component2;
namespace my_application {
namespace platform_logs {
class backtrace_log {
//code that creates instances of my_namespace1::component1 and my_namespace2::component2
};
}
}
On the other hand this next example is fine, but to be used with caution. It only makes sense if you want to include all those symbols in your API. This is often the case with internal project name spaces but less likely with third party namespaces.
I would especially avoid even this with very large namespaces like std::.
#include <memory>
namespace my_application {
namespace platform_logs {
using my_namespace1::component1;
using my_namespace2::component2;
class backtrace_log {
//code that creates instances of my_namespace1::component1 and my_namespace2::component2
};
}
}
In your first example whenever you include
backtrace.h
in another file that file will also use those namesapces. So if by mistake someone wrote "blax" in a file where you included backtrace.h and "blax" also happened to be a class or function in you namespace, e.g.:
my_namespace1::component1::blax
the compiler might take his "blax" to mean "my_namespace1::component1::blax"
By placing the using namespace inside another namespace you simply include all those definitions into that namespace, in the previous example, if you went with version two of the code that collision wouldn't happen since "my_namespace1::component1::blax" would be included as my_application::platform_logs::blax.
Overall most coding guides would encourage you to:
a) Prefer to not ever do "using namespace" or at least use it just to shorten (e.g. using short_namespace = first_namespace::another_namepsace::last_namespace)
b) If you do "using namespace" do so in the source file (i.e .cpp or .c files), since the definitions in those files are not included
c) If you do "using namespace" in headers nest it in another namespace (like in your example) so that it doesn't "leak" into the scope of other file which include your header
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.
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.
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.
I have a C++ project (VC++ 2008) that only uses the std namespace in many of the source files, but I can't find the "right" place to put "using namespace std;".
If I put it in main.cpp, it doesn't seem to spread to my other source files. I had it working when I put this in a header file, but I've since been told that's bad. If I put it in all of my .cpp files, the compiler doesn't recognize the std namespace.
How should this be done?
You generally have three accepted options:
Scope usage (std::Something)
Put using at the top of a source file
Put using in a common header file
I think the most commonly accepted best practice is to use #1 - show exactly where the method is coming from.
In some instances a file is so completely dependent on pulling stuff in from a namespace that it's more readable to put a using namespace at the top of the source file. While it's easy to do this due to being lazy, try not to succumb to this temptation. At least by having it inside the specific source files it's visible to someone maintaining the code.
The third instance is generally poor practice. It can lead to problems if you're dependent on more than one external source file both of which may define the same method. Also, for someone maintaining your code it obfuscates where certain declarations are coming from. This should be avoided.
Summary:
Prefer to use scoped instances (std::Something) unless the excessive use of these decreases the legibility and maintainability of your code.
In your headers, the best thing I think is just to fully qualify the namespace, say of a member
#include <list>
class CYourClass
{
std::list<int> myListOfInts;
...
};
You can continue to fully qualify in any function in a cpp
int CYourClass::foo()
{
std::list<int>::iterator iter = myListOfInts.begin();
...
}
you really never need "using namespace std" anywhere. Only if you find you are typing std:: too much, thats when its good to throw in a "using namespace std" to save your own keystrokes and improve the readability of your code. This will be limited to the scope of the statement.
int CYourClass::foo()
{
using namespace std;
list<int>::iterator iter = myListOfInts.begin();
...
}
You can put it in multiple places - in each .cpp file.
Essentially, you need to make a choice:
1) "do the right thing" by including using namespace std in all your cpp files, or
2) add using namespace std in some common header file.
Different people will have different opinions of which is best, however if you ask me, I'd chose to put using namespace std in a common header. In my opinion, the std namespace is just that - "standard" and any name conflicts need to be resolved at code level, rather than relying on namespaces.
The namespace doesn't 'spread' to other files.
You have to put it in each of the files, or just explicitly call out your classes.
either:
using namespace std;
blah << x;
or:
std::blah << x;
The choice is a style choice, either works in practice.
If the compiler doesn't 'recognize' the namespace it's because you haven't included the definition file that declares it ( i.e. include )
It's not a good idea to spread over your code using namespace std;only because it's seem convenient to you to do so. But if you insist on it you can wrap your own code into that name space. And only later when you will actually will make a use of your function/classes in the main file you will define using namespace std;. Just to emphasize that I'm saying, here the example:
namespace std
{
class MyNewClass
{
public:
MyNewClass( ) { out << "Hello there" << endl;};
};
};
int main( )
{
std::MyNewClass tmp;
};