Shorten nested namespace names - c++

If you use nested namespaces, declarations in header files can get very long and unreadable.
//header1
namespace test { namespace test1 {
class Test {};
} } //namespace
In header2 of the program:
#include "header1"
namespace test2 {
class Test1 {
void test(test::test1::Test &test) {}
void test1(test::test1::Test &test) {}
void test2(test::test1::Test &test1, test::test1::Test &test2) {}
};
}
Are there any possibilities to shorten the names in header2?

Here is my favorite technique:
#include "header1"
namespace test2 {
class Test1 {
private:
typedef ::test::test1::Test MeaningfulName;
void test(MeaningfulName &test) {}
void test1(MeaningfulName &test) {}
void test2(MeaningfulName &test1, MeaningfulName &test2) {}
};
}
I make my typedef aliases private, but I put them right at the beginning of the class declaration. It doesn't matter that they're private to the rest of the program because nobody will be using the aliased name, they will be using the actual type name or their own alias for the name.
I also really prefer to use anchored namespace names to avoid later surprises. My rule for this is that I always use an anchored name unless the namespace is one I control and/or is part of the current project or package or whatever. Then I will use the shortest possible relative name. If that relative name would start from the root namespace, I still often use an anchored name.
The main problem is the digraph <: which will crop up in template declarations a lot once you start using anchored names more often. You have to put in a space to avoid it, especially since digraph processing happens at a really early stage and can give you some very weird error messages.

you can alias namespaces, like this:
namespace tt=test::test1;

There are ways to shorten the names by using aliases or the using keyword, but they're almost always a bad idea. Namespaces exist for a reason, that reason is to keep things separated. As soon as you put the using keyword in a header file you break that separation, and there's no point in using namespaces at all. Inside your cpp files you can feel free to have using namespace test1 if you're implementing stuff in test1, but I would recomend you not do that in your header file as it is the same as putting it at the top of every single cpp file in which that header is included.
What you have to remember is that declaring something in a header is the same as declaring it in every cpp file in which that header is included. It would also be worth asking yourself, "If you're using test1 inside test2 so often, why are they different namespaces?"

In file header2.h
using namespace test::test1;

While this is an old question I feel like I should put forward my solution to this issue, particularly since it's one of the first results that pop-up in google for the subject and may help others.
This method is definitely not the safest as it involves using preprocessor directives but I've taken a liking to using #define and #undef to shorten namespaces in headers.
Here's an example:
#include "header1"
#define shortNS test::test1
namespace test2 {
class Test1 {
void test(shortNS::test &test) {}
void test1(shortNS::test &test) {}
void test2(shortNS::test &test1, shortNS::test &test2) {}
};
}
#undef shortNS
Basically it works by creating a define called "shortNS" that the preprocessor blindly replaces with "test::test1" where ever it occurs after the definition. The issue of course with defining a macro is that it's not limited by scope in any way shape or form, which can wreak havoc and has been known to cause any unsuspecting programmer to loose their mind whilst attempting to debug it.
So to prevent that once we're done with the define we #undef shortNS to tell the preprocessor to stop replacing "shortNS" with "test::test1". This allows us to simulate scope to some degree. In the example above I limited shortNS to the 'scope' of the file.
Here's a brief list of pros/cons off the top of my head.
Pros:
Allows you to manually limit scope. (Only need it for half a function? Sure.)
Transparent to anyone including the file.
No left-over namespace like with "namespace a = b::c"
No namespace collisions from "using namespace"
Doesn't bring a namespace into the current namespace (like "using namespace" does)
Cons:
Any errors in the definition of the shortened namespace will appear wherever it is used never at the macro itself.
If you include a file inside a #define #undef "block" the define will be used in the included file which may cause unintended results and/or headaches.
If you forget to #undef it can/will wreck havoc and you will go insane.
It's a little clunky.
People who are maintaining your code will hate you.
Long story short, if you're comfortable with macros and don't mind pulling your hair out trying to debug it when it goes wrong, go ahead. The preprocessor is a very, very powerful thing but it's like taping a bit of C4 to your foot and mashing the keypad to set the timer - you don't know when it's going to blow your leg off.

Related

Using namespaces and includes

The question might be trivial (and possibly a duplicate).
As far as I understand, a C/C++ header file (with a using namespace in it), when used by other source files, it is copied right at the point where the #include directive was in that source file.
Also, given that a source file uses a relatively large number of include directives and that there may be a couple of "redefinitions" for the entire standard library (simply targeted at different implementations).
Here is the main question: How do I know which namespaces am I currently using at any point in the source file if the source file has no using namespace statement?
I'm reading through source files and I have no idea which namespace is being used.
One can override the namespace cleverness by using something like ::std::getline().
If there is no easy way of determining the namespace, is it fair to refactor those files, such that where say string is used to replace it with ::std::string?
If you don't have a using namespace ... directive you're not using any namespace. In general, your code should refer to things in the standard library with their full names, e.g., std::cout, std::get_line(), std::string.
Yes, you can save your self some typing at the expense of loss of clarity and sometimes mysterious compilation failures or, worse, runtime failures with using namespace std;. After that, you don't have to put std:: in front of the names of things in the standard library: cout, get_line(), string. The using directive puts those names into the global namespace, along with a bunch of sludge that you probably aren't interested in.
If you use something like using namespace std; it should appear only in a source file, never in a header. That way you can tell which namespaces have been "used" by looking at the top of the file. You shouldn't have to track through all your headers for stray using directives.
using namespace does not mean that you currently use this specific namespace. It means, that all types, variables and functions from this namespace are now in your global namespace, for this translation unit. So, you might have multiple of these statements.
This is why header files should never use using namespace. There is no easier way than using std::string within a header file, you should always be very explicit about the namespace without using namespaces.
Having used using namespace xxx, there is no way of finding out that xxx is now in global namespace, I am afraid.
using namespace does not do what you expect...
If you want to place functions, classes or variables in a namespace, you do it this way:
namespace foo
{
void f();
}
namespace bar
{
void f();
}
This declares two functions f in namespaces foo and bar respectively. The same you will find in header files; if there is no namespace specified as above, then the function/class/variable is in global namespace. Nothing more.
using namespace now allows you to use functions from a namespace without having to specify it explicitly:
// without:
foo::f();
bar::f();
f(); // unknown!
using namespace foo;
foo::f(); // still fine...
bar::f();
f(); // now you call foo::f
Be aware that this is bad practice, though (the link refers to namespace std, but same applies for all namespaces).
This is even worse in header files: there is no way to undo the effect of a declared using namespace <whatever> again – so you impose it on all users of your header, possibly causing great trouble to some of them. So please don't ever use it in header files.
There are three approaches I can think of right now:
Use the IDE: A modern development environment should be able (possibly with the help of plug-ins) to analyze your code while you edit, and tell you the authoritative qualified name of any identifier you hover the mouse cursor over.
Of course this is not an option if you are not using an IDE, and sometimes even IDEs may get confused and give you wrong information.
Use the compiler and guesswork: If you already have a hunch which namespace you might be in, you can define some object, reference it via qualified name, and see if the code compiles, like so:
const int Fnord = 1;
const int* Probe = &::solid::guess::Fnord;
One caveat is that it may give misleading results if using namespace or anonymous namespaces are involved.
Use the preprocessor: Most compilers define a preprocessor macro that tells you the name of the function it is used in, which may include the namespace; for example, on MSVC, __FUNCTION__ will do just this. If the file contains a function that you know will be executed, you can have that function tell you its authoritative qualified name at run-time, like so:
int SomeFunction(void)
{
printf("%s\n", __FUNCTION__);
}
If you can't use standard output, you might store the value in a variable and use a debugger to inspect it.
If you can find no such function, try defining a class with a static instance of itself, and placing the code in the constructor.
(Unfortunately I can't think of a way to inspect the macro's value at compile-time; static_assert came to my mind, but it can't be used inside functions, and __FUNCTION__ can't be used outside.)
The macro is not standardized though, and may not include the namespace (or it may not exist at all). On GCC for instance, __FUNCTION__ will only give you the unqualified name, and you will have to use __PRETTY_FUNCTION__ instead.
(As of C99 and C++11 there does exist a standardized alternative, __func__, but the format of the function name is unspecified, and may or may not include the namespace. On GCC it does not.)

Why are include directives on top of header files?

I was once told in a programming class that C++ had achieved a better readability by letting the programmer declare its variable anywhere in a function block. This way, the variables were grouped together with the section of the code that dealt with it.
Why don’t we do the same for includes?
Put differently, why is it discouraged to put the include file next to the definition that will actually use it?
parser::parser()
{
// some initialization goes there which does not make use of regex
}
#include <boost/regex.hpp>
parser::start()
{
// here we need to use boost regex to parse the document
}
One of the reasons for this is that #include are context-less, they are just plain text inclusion, and having it in the middle of the code might have some unwanted effects. Consider for example that you had a namespace, and all your code in this file belongs to the namespace:
// Include on demand:
namespace ns {
void f() {} // does not need anything
//... lots of other lines of code
#include <vector>
void g() { std::vector<int> v; }
}
Now that might even compile fine... and wrong. because the inclusion is inside a namespace, the contents of the file are dumped inside ns and the included file declares/defines ::ns::std::vector. Because it is header only it might even compile fine, only to fail when you try to use that in an interface with a different subsystem (in a different namespace) -- This can be fixed, you only need to close all contexts, add the inclusion and reopen the same contexts...
There are other situations where the code in your translation unit might actually affect the includes. Consider, for example, that you added a using namespace directive in your translation unit. Any header included after that will have the using namespace directive in place, and that might also produce unwanted effects.
It could also be more error prone in different ways. Consider two headers that defined different overloads of f for int and double. You might add one (say the int version) towards the beginning of the file and use it, then add the other and use it. Now if you call f(5.0) above the line where the second header is included, the int version will be called --only overload available to the compiler at this point--, which would be a hard to catch error. The exact same line of code would have completely different meaning in different places in your file (admittedly that is already the case, but within the declarations in your file it is easier to find which is the one being picked up and why)
In general, the includes declare elements that you will be using in your component, and having them on the top provides a list of dependencies in a quick glance.
Imagine the following file:
#include <someheader>
namespace myns {
void foo() {
}
void bar() {
// call something from someheader:
func();
}
}
It might be tempting to put #include <someheader> nearer the point of usage. That would be fine iff you wrote the following instead:
namespace myns {
void foo() {
}
}
#include <someheader>
namespace myns {
void bar() {
// call something from someheader:
func();
}
}
The problem is in a medium/large sized file it's rather easy to loose track of quite how deeply nested you are inside namespaces (and other #ifdefs), depending on your indentation style. You might come back later and decide to move things around, or add another nested namespace.
So, if you write the #include at the top always you can never get bitten by accidentally writing something like:
namespace myns {
void foo() {
}
// Whoops, this shouldn't be inside myns at all!
#include <someheader>
void bar() {
// call something from someheader:
func();
}
}
which would be somewhere between wrong and very wrong depending on what exactly is in <someheader>. (You could for example end up with UB, by violating the ODR having multiple definitions which although otherwise legal and identical sequence of tokens match different functions and so violate § 3.2.5).
It's discouraged because most programmers are used to includes at the top of the file. Force of habit I think, and for consistency with 99% of existing code.
When I personally want to see what headers are included, I only look at the top. In special (and thankfully rare) cases where something is fishy, I might look for includes in the whole file.
To the compiler it makes no difference anyway.

Declaring using statement after namespace declaration

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).

How to use a single namespace across files?

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;
};

Do you prefer explicit namespaces or 'using' in C++?

When using C++ namespaces, do you prefer to explicitly name them, like this:
std::cout << "Hello, world!\n";
Or do you prefer using namespace:
using namespace std;
cout << "Hello, world!\n";
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.
I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better.
Extra typing is not the issue here. The problem with explicitly qualified names is the visual clutter. Let's face it, C++ syntax is untidy. No need to make this worse by needlessly making names longer and sprinkling the code generously with ::s.
I'm with Jeff Atwood: The Best Code is No Code At All. This is so true.
Namespace imports are a great way of reducing clutter with no drawback: As long as the scope of opened namespaces is reduced to a single compilation unit1, name conflicts, should they appear, can be resolved easily.
Why explicit names should (in general) be more readable has always been a mystery to me. The readers should generally know the code good enough to be able to deduce semantics. If they aren't, the code needs fixing anyway.
1) Corollary: no using in headers!
I always use using namespace for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use using namespace to avoid polluting the global namespace of the #including source.
My general rule is always explicitly use the namespace in headers, and usually use using in the code. The reason for the former is to make it explicitly clear in every part of the definition what is being used, and the reason for the latter is that it makes it easy to use replacements from another namespace if that becomes necessary. i.e. if we want to start using foo::string instead of std::string we just need to update the header and the using statement rather than replacing every instance of std::string with foo::string in the code.
Of course, that is less useful for classes that reside in the std:: namespace, since even if you replace one class you're still likely to use others in std, and may run into ambiguity issues, but that was just an example.
using and using namespace are Very Very useful to render the code more readable - remove clutter.
But in any case where it makes it harder to find out where a symbol comes from, I refuse importing it's whole namespace.
I try to limiit the scope of the imported namespaces:
void bar() {
// do stuff without vector
{ using std::vector;
// do stuff with vector
}
// do stuff without vector
}
For "generally known" libraries, like std, I would dare using using namespace std. There is reason to believe everyone reading this code knows these symbols.
As a sidenote, the using keyword is also used to indicate that a derived class also exports the overloaded members of its superclass.
class A {
void f( A );
void f( bool );
};
class B : public A {
using A::f; // without this, we get a compilation error in foo()
void f(bool);
};
void foo() {
B b;
b.f( A() ); // here's a compilation error when no `using` is used in B
}
I only use explicit namespaces when there's some ambiguity. It is more readable, but the extra typing is too tedious, and you have to assume other developers have a baseline level of familiarity with standard libraries.
The only other times I spell out a namespace are when I'm only using it once or twice, like adding in a quick debug statement, or if I'm using some non-standard library.
I typically declare the namespace at file scope, but if you're mixing namespaces it might make sense to put the declaration closer to the point where it's used, in function scope.
using at function scope, or if the function is very small (often is), just explicit namespace
I tend to explicitly import the names that I need at the top of the .cpp file, so...
using std::cout;
using std::endl;
etc...
That way I have control over the names that I use and it's easy to see where they come from and the code isn't cluttered at the point of use.
In the rare cases where I am using two names from different namespaces I fully qualify them at the point of use.
I always use fully qualified names in headers and hardly ever use 'using namespace x' anywhere...