Declaring using statement after namespace declaration - c++

I am writing a utility library which is made up of several "Packages". The classes in each package are contained in various namespaces. I have an idea as to how I can simplify the situation by automatically declaring using statements at the end of class declarations (see below), this will avoid having the programmer do it in a cpp file.
namespace Utility
{
class String
{
// Class Implementation
};
}
using Utility::String;
My understanding is that if the user includes the header String.h and String is in Utility then the programmer will want to use String. Obviously this could be bad if there are outside classes chain including a bunch of files which dirty up the namespace so I thought how about making it a #define instead.
namespace Utility
{
class String
{
// Class Implementation
};
}
#ifdef AUTO_DECLARE_NAMESPACE
using Utility::String;
#endif
That way, programmers that want this extended functionality can get it.
Would this a good idea or is there something I'm overlooking?

There is no point in using namespaces if you are just going to add a using declaration for each and every name declared in the namespace.
Let users of your header files decide how they want to use the headers. If someone wants to use a using declaration, let him do it in the .cpp file directly; this will make the code in that .cpp file clearer since it will be apparent where the name originated.

This seems at best pointless, and at worst annoying.
What is wrong with having developers decide which namespaces to use and what to qualify fully?

Honestly, I believe that's what the using namespace directive is for. There's no need for you to add this preprocessor mechanism, considering the using namespace directive does just that.

Couldn't you have another .h file with all your usings like my_lib_import_names.h and just #include that to get what you want?
You would probably have problem with classes not being declared but you could probably bypass it by using something like:
#ifdef UTILITY_STRING_H_
using Utility::String;
#endif
..
#ifdef UTILITY_SOMETHING_ELSE_H
using Utility::SomethingElse;
#endif
..
What do you think?
That way you could retain the "expected" behavior in your library .h but also have your the way you like. You also get to keep the benefit of the namespace over your classes (at the expense of having to maintain your new .h file).

Related

Why there set macro definition and namespace in C++ .h file?

I am reading this open source project:
I have two questions:
I found the
#ifndef _RANGE_REQUEST_GENERATOR_H_
#define _RANGE_REQUEST_GENERATOR_H_
#endif
and I only find the _RANGE_REQUEST_GENERATOR_H_ in this .h file, other place not use it.
so, what's the usage of the macro definition?
there use the namespace wrap the functions.
namespace slowhttptest {
//functions
}
what's the purpose? why do not use std, is it better?
Question #1
See Purpose of Header guards
Question #2
Consider the case where you are using libraries. And two libraries would both like to have a function named Push(). We could name them: LibraryFoo_Push(), and LibraryBar_Push(), or we could use namespaces. Namespaces have some additional benefits with lookups as well.
And see C++ When is it OK to extend the `std` namespace? for when you are allowed to add stuff to the std namespace.

"using namespace" in c++ headers [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 1 year ago.
In all our c++ courses, all the teachers always put using namespace std; right after the #includes in their .h files. This seems to me to be dangerous since then by including that header in another program I will get the namespace imported into my program, maybe without realizing, intending or wanting it (header inclusion can be very deeply nested).
So my question is double: Am I right that using namespace should not be used in header files, and/or is there some way to undo it, something like:
//header.h
using namespace std {
.
.
.
}
One more question along the same lines: Should a header file #include all the headers that it's corresponding .cpp file needs, only those that are needed for the header definitions and let the .cpp file #include the rest, or none and declare everything it needs as extern?
The reasoning behind the question is the same as above: I don't want surprises when including .h files.
Also, if I am right, is this a common mistake? I mean in real-world programming and in "real" projects out there.
Thank you.
You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header. There's no way to undo a using namespace which is another reason it's so dangerous. I typically just use grep or the like to make sure that using namespace isn't being called out in headers rather than trying anything more complicated. Probably static code checkers flag this too.
The header should include just the headers that it needs to compile. An easy way to enforce this is to always include each source file's own header as the first thing, before any other headers. Then the source file will fail to compile if the header isn't self-contained. In some cases, for example referring to implementation-detail classes within a library, you can use forward declarations instead of #include because you have full control over the definition of such forward declared class.
I'm not sure I would call it common, but it definitely shows up once in a while, usually written by new programmers that aren't aware of the negative consequences. Typically just a little education about the risks takes care of any issues since it's relatively simple to fix.
Item 59 in Sutter and Alexandrescu's "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices":
59. Don’t write namespace usings in a header file or before an #include.
Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.
Corollary: In header files, don't write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names.
A header file is a guest in one or more source files. A header file that includes using directives and declarations brings its rowdy buddies over too.
A using declaration brings in one buddy. A using directive brings in all the buddies in the namespace. Your teachers' use of using namespace std; is a using directive.
More seriously, we have namespaces to avoid name clash. A header file is intended to provide an interface. Most headers are agnostic of what code may include them, now or in the future. Adding using statements for internal convenience within the header foists those convenient names on all the potential clients of that header. That can lead to name clash. And it's just plain rude.
You need to be careful when including headers inside of headers. In large projects, it can create a very tangled dependency chain that triggers larger/longer rebuilds than were actually necessary. Check out this article and its follow-up to learn more about the importance of good physical structure in C++ projects.
You should only include headers inside a header when absolutely needed (whenever the full definition of a class is needed), and use forward declaration wherever you can (when the class is required is a pointer or a reference).
As for namespaces, I tend to use the explicit namespace scoping in my header files, and only put a using namespace in my cpp files.
With regards to "Is there some way to undo [a using declaration]?"
I think it is useful to point out that using declarations are affected by scope.
#include <vector>
{ // begin a new scope with {
using namespace std;
vector myVector; // std::vector is used
} // end the scope with }
vector myOtherVector; // error vector undefined
std::vector mySTDVector // no error std::vector is fully qualified
So effectively yes. By limiting the scope of the using declaration its effect only lasts within that scope; it is 'undone' when that scope ends.
When the using declaration is declared in a file outside of any other scope it has file-scope and affects everything in that file.
In the case of a header file, if the using declaration is at file-scope this will extend to the scope of any file the header is included in.
Check out the Goddard Space Flight Center coding standards (for C and C++). That turns out to be a bit harder than it used to be - see the updated answers to the SO questions:
Should I use #include in headers
Self-sufficient headers in C and C++
The GSFC C++ coding standard says:
§3.3.7 Each header file shall #include the files it needs to compile, rather than forcing users to #include the needed files. #includes shall be limited to what the header needs; other #includes should be placed in the source file.
The first of the cross-referenced questions now includes a quote from the GSFC C coding standard, and the rationale, but the substance ends up being the same.
You are right that using namespace in header is dangerous.
I do not know a way how to undo it.
It is easy to detect it however just search for using namespace in header files.
For that last reason it is uncommon in real projects. More experienced coworkers will soon complain if someone does something like it.
In real projects people try to minimize the amount of included files, because the less you include the quicker it compiles. That saves time of everybody. However if the header file assumes that something should be included before it then it should include it itself. Otherwise it makes headers not self-contained.
You are right. And any file should only include the headers needed by that file. As for "is doing things wrong common in real world projects?" - oh, yes!
Like all things in programming, pragmatism should win over dogmatism, IMO.
So long as you make the decision project-wide ("Our project uses STL extensively, and we don't want to have to prepend everything with std::."), I don't see the problem with it. The only thing you're risking is name collisions, after all, and with the ubiquity of STL it's unlikely to be a problem.
On the other hand, if it was a decision by one developer in a single (non-private) header-file, I can see how it would generate confusion among the team and should be avoided.
I believe you can use 'using' in C++ headers safely if you write your declarations in a nested namespace like this:
namespace DECLARATIONS_WITH_NAMESPACES_USED_INCLUDED
{
/*using statements*/
namespace DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED
{
/*declarations*/
}
}
using namespace DECLARATIONS_WITH_NAMESPACES_USED_INCLUDED::DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED;
This should include only the things declared in 'DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED' without the namespaces used. I have tested it on mingw64 compiler.

C++ include header problem

I am new to c/c++, I am confused about followings:
Whether I should put class declarations in its own header file, and actual implementation in another file?
Whether I should put headers like <iostream> in the example.h file or in example.cpp file?
If all the classes need to use <iostream>, and I include a class's header file into another class's header, does it mean I included <iostream> twice?
If I use a lot STL classes, what is a good practice to use std::?
1.Whether I should put class declarations in its own header file,
and actual implementation in another
file?
You can write the definition of a class, and the definition of the members of the class separately in the same header file if you are manipulating templates. Also, if you want to make your members function inline, you can define them inside the class definition itself. In any other case, it is better to separate the definition of the class (.hpp file) and the definition of the members of the class (.cpp).
2.Whether I should put headers like in the example.h file or in example.cpp
file?
It Depends on if you need those headers in the example.h file or in your .cpp file only.
3.If all the classes need to use , and I include a class's header file into
another class's header, does it mean I
included twice?
It happens if you don't wrap your class definitions by the following macros:
#ifndef FOO_HPP
#define FOO_HPP
class {
...
};
#endif
5.If I use a lot STL classes, what is a good practice to use std::?
I think it is better whenever you can to use std:: each time instead of using namespace std. This way you will use only the namespaces that you need and your code will be more readable because you will avoid namespace conflicts (imagine two methods that have the same name and belong to two different namespaces).
But most importantly where is question number 4 anyway?
Generally, yes. It helps with organization. However, on small projects it may not be that big of a deal.
I'm having trouble understanding the question here. If you're asking where to put the #include directive, the implementation file should include the header file.
Yes, but the use of include guards prevents multiple inclusions.
You normally should, but for relatively small projects you may avoid having an implementation file as much as possible;
If your header is using only incomplete types from the <iostream>, you can avoid including it, but you'll need forward declarations for these types (see When to use forward declaration?). Yet, for simplicity, if the type uses template, I normally include the respective header;
No. The include guards guarantee that a header is included only once in the same translation unit;
A common good practice is to not put using namespace std in a header file. Be aware of namespace conflicts too;
Typically, you do put class declarations (including declarations of members) into header files and definitions of member functions (methods) in source files. Headers usually have names like *.h or *.hpp. As to point 3, you should put include guards into your headers so they can be safely included multiple times in the same source file; then you can include them everywhere you need them. I don't understand point #5: are you asking about when to use std:: namespace qualification?
For the "included twice" problem, here is a common pattern for your header files:
// _BLAHCLASS_H_ should be different for each header, otherwise things will Go Bad.
#ifndef _BLAHCLASS_H_
#define _BLAHCLASS_H_
... rest of header ...
#endif
As long as they're not templates, generally yes. Templates (for better or worse) have to be put in headers.
I prefer to make each of my headers "standalone", so if any other header is needed for it to function, it includes that header itself (e.g., if I have a class that uses std::string, the header for that class will #include <string>.
No. With a few special exceptions, the standard headers are required to be written so you can include them more than once without it changing anything (the primary exception is assert.h/cassert, which it can make sense to include more than once).
I'm not sure exactly what you're asking. If you're asking about a using directive like using namespace std;, then it's generally (though certainly not universally) disliked. A using declaration like using std::vector; is generally considered less problematic.

Does using a C++ namespace increase coupling?

I understand that a C++ library should use a namespace to avoid name collisions, but since I already have to:
#include the correct header (or forward declare the classes I intend to use)
Use those classes by name
Don't these two parameters infer the same information conveyed by a namespace. Using a namespace now introduces a third parameter - the fully qualified name. If the implementation of the library changes, there are now three potential things I need to change. Is this not, by definition an increase in coupling between the library code and my code?
For example, look at Xerces-C: It defines a pure-virtual interface called Parser within the namespace XERCES_CPP_NAMESPACE. I can make use of the Parser interface in my code by including the appropriate header file and then either importing the namespace using namespace XERCES_CPP_NAMESPACE or prefacing declarations/definitions with XERCES_CPP_NAMESPACE::.
As the code evolves, perhaps there is a need to drop Xerces in favour of a different parser. I'm partially "protected" from the change in the library implementation by the pure-virtual interface (even more so if I use a factory to construct my Parser), but as soon as I switch from Xerces to something else, I need to comb through my code and change all my using namespace XERCES_CPP_NAMESPACE and XERCES_CPP_NAMESPACE::Parser code.
I ran into this recently when I refactored an existing C++ project to split-out some existing useful functionality into a library:
foo.h
class Useful; // Forward Declaration
class Foo
{
public:
Foo(const Useful& u);
...snip...
}
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
Foo::Foo(const Useful& u)
{
... snip ...
}
Largely out of ignorance (and partially out of laziness) at the time, the all of the functionality of useful.lib was placed in the global namespace.
As the contents of useful.lib grew (and more clients started to use the functionality), it was decided to move all the code from useful.lib into its own namespace called "useful".
The client .cpp files were easy to fix, just add a using namespace useful;
foo.cpp
#include "foo.h"
#include "useful.h" // Useful Library
using namespace useful;
Foo::Foo(const Useful& u)
{
... snip ...
}
But the .h files were really labour intensive. Instead of polluting the global namespace by putting using namespace useful; in the header files, I wrapped the existing forward declarations in the namespace:
foo.h
namespace useful {
class Useful; // Forward Declaration
}
class Foo
{
public:
Foo(const useful::Useful& u);
...snip...
}
There were dozens (and dozens) of files and this ended up being a major pain! It should not have been that difficult. Clearly I did something wrong with either the design and/or implementation.
Although I know that library code should be in its own namespace, would it have been advantageous for the library code to remain in the global namespace, and instead try to manage the #includes?
It sounds to me like your problem is due primarily to how you're (ab)using namespaces, not due to the namespaces themselves.
It sounds like you're throwing a lot of minimally related "stuff" into one namespace, mostly (when you get down to it) because they happen to have been developed by the same person. At least IMO, a namespace should reflect logical organization of the code, not just the accident that a bunch of utilities happened to be written by the same person.
A namespace name should usually be fairly long and descriptive to prevent any more than the most remote possibility of a collision. For example, I usually include my name, date written, and a short description of the functionality of the namespace.
Most client code doesn't need to (and often shouldn't) use the real name of the namespace directly. Instead, it should define a namespace alias, and only the alias name should be used in most code.
Putting points two and three together, we can end up with code something like this:
#include "jdate.h"
namespace dt = Jerry_Coffin_Julian_Date_Dec_21_1999;
int main() {
dt::Date date;
std::cout << "Please enter a date: " << std::flush;
std::cin>>date;
dt::Julian jdate(date);
std::cout << date << " is "
<< jdate << " days after "
<< dt::Julian::base_date()
<< std::endl;
return 0;
}
This removes (or at least drastically reduces) coupling between the client code and a particular implementation of the date/time classes. For example, if I wanted to re-implement the same date/time classes, I could put them in a different namespace, and switch between one and the other just by changing the alias and re-compiling.
In fact, I've used this at times as a kind of compile-time polymorphism mechanism. For one example, I've written a couple versions of a small "display" class, one that displays output in a Windows list-box, and another that displays output via iostreams. The code then uses an alias something like:
#ifdef WINDOWED
namespace display = Windowed_Display
#else
namespace display = Console_Display
#endif
The rest of the code just uses display::whatever, so as long as both namespaces implement the entire interface, I can use either one, without changing the rest of the code at all, and without any runtime overhead from using a pointer/reference to a base class with virtual functions for the implementations.
The namespace has nothing to do with coupling. The same coupling exists whether you call it useful::UsefulClass or just UsefulClass. Now the fact that you needed to do all that work refactoring only tells you to what extent your code does depend on your library.
To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.
Still, coupling and namespaces are just unrelated. A rose would smell as sweet by any other name, and your classes are as coupled in any other namespace.
(a) interfaces/classes/functions from the library
Not any more than you already have. Using namespace-ed library components helps you from namespace pollution.
(b) implementation details inferred by the namespace?
Why? All you should be including is a header useful.h. The implementation should be hidden (and reside in the useful.cpp and probably in a dynamic library form).
You can selectively include only those classes that you need from useful.h by having using useful::Useful declarations.
I'd like to expand on the second paragraph of David Rodríguez - dribeas' answer (upvoted):
To ease the forwarding you could have written a forward header (there are a couple in the STL, you can surely find it in libraries) like usefulfwd.h that only forward defined the library interface (or implementing classes or whatever you need). But this has nothing to do with coupling.
I think this points to the core of your problem. Namespaces are a red herring here, you were bitten by underestimating the need to contain syntactic dependencies.
I can understand your "laziness": it is not right to overengineer (enterprise HelloWorld.java), but if you keep your code low-profile in the beginning (which is not necessarily wrong) and the code proves successful, the success will drag it above its league. the trick is to sense the right moment to switch to (or employ from the first moment the need appears) a technique that scratches your itch in a forward compatible way.
Sparkling forward declarations over a project is just begging for a second and subsequent rounds. You don't really need to be a C++ programmer to have read the advice "don't forward-declare standard streams, use <iosfwd> instead" (though it's been a few years when this was relevant; 1999? VC6 era, definitely). You can hear a lot of painful shrieks from programmers who didn't heed the advice if you pause a little.
I can understand the urge to keep it low-brow, but you must admit that #include <usefulfwd.h> is no more pain than class Useful, and scales. Just this simple delegation would spare you N-1 changes from class Useful to class useful::Useful.
Of course, it wouldn't help you with all the uses in the client code. Easy help: in fact, if you use a library in a large application, you should wrap the forward headers supplied with the library in application-specific headers. Importance of this grows with the scope of the dependency and the volatility of the library.
src/libuseful/usefulfwd.h
#ifndef GUARD
#define GUARD
namespace useful {
class Useful;
} // namespace useful
#endif
src/myapp/myapp-usefulfwd.h
#ifndef GUARD
#define GUARD
#include <usefulfwd.h>
using useful::Useful;
#endif
Basically, it's a matter of keeping the code DRY. You might not like catchy TLAs, but this one describes a truly core programming principle.
If you have multiple implementations of your "useful" library, then isn't it equally probable (if not under your control) that they would use the same namespace, whether it be the global namespace or the useful namespace?
Put another way, using a named namespace versus the global namespace has nothing to do with how "coupled" you are to a library/implementation.
Any coherent library evolution strategy should maintain the same namespace for the API. The implementation could utilize different namespaces hidden from you, and these could change in different implementations. Not sure if this is what you mean by "implementation details inferred by the namespace."
no you are not increasing the coupling. As others have said - I dont see how the namespace use leaks the implementation out
the consumer can choose to do
using useful;
using useful::Foo;
useful::Foo = new useful::Foo();
my vote is always for the last one - its the least polluting
THe first one should be strongly discouraged (by firing squad)
Well, the truth is there's no way to easily avoid entanglement of code in C++. Using global namespace is the worst idea, though, because then you have no way to pick between implementations. You wind up with Object instead of Object. This works ok in house because you can edit the source as you go but if someone ships code like that to a customer they should not expect them to be for long.
Once you use the using statement you may as well be in global, but it can be nice in cpp files to use it. So I'd say you should have everything in a namespace, but for inhouse it should all be the same namespace. That way other people can use your code still without a disaster.

why using directive in C++ is not encouraged?

I read that using directive is not encouraged in C++ saying never put using directives in header files. Why is it like that? Any hint for me?
Thanks!
using namespace x; is a very bad idea, since you have no idea what names you are importing, even with the standard library.
However: using std::cout; and similar statements are a very good idea, because they import symbols explicitly, and make code more readable (though it still might not be a good idea to put them in the global scope in header files).
If you are talking about the 'using' directive, the reason for not using it is because if you say
using namespace std;
in a header file, all files that #include that header will be forced to use that namespace, and that could cause problems.
Because it can break working code, when trying to add your header, if your header namespace trample other namespace that defined in the past-working code.
It is similar to no to declare static variables in header files. Adding using statement in header files will bring the namespace into .cpp files that include the header file. It is not necessary. In the worse case, you may have to change some variable or functions names in .cpp in order to avoid naming conflicts.