Using Directives in Implementation Files - c++

In C++ Primer, there is one tips says:
One place where using directives are useful is in the implementation
files for the namespace itself.
I guess this is just for using shorthand names? I am not sure how it is different from just surrounding the implementation with
namespace namespace_name
{
}
Thanks.

That applies to modifications to your own namespaces. The purpose of using directives is to import symbols from a different namespace. For example, an infamous idiom:
namespace my_stuff
{
template <typename Container>
void my_fn( Container& xs )
{
using std::begin;
using std::end;
std::sort( begin(xs), end(xs) );
}
}
Everything happens in your my_namespace, but it makes available the std::begin() and std::end() functions if needed. If a more local definition for begin() and end() exists that better matches the Container type, then it will be used instead. If you had simply wrapped everything in the std namespace, this useful ability would be lost.
Hope this helps.

I am not sure how it is different from just surrounding the implementation with namespace namespace_name { }
This is to put your own code within a namespace, as opposed to using some name from another namespace. Say you write a draw function inside the Graphics namespace -- to do this, you wrap draw's code in namespace Math { void draw() { /* some code */ } } and to use it you'd do Graphics::draw. However, when you need to use a function, say, gamma in the Math namespace (which you didn't write), you've to call it Math::gamma for the compiler to know where to search for gamma. Alternatively, you may use shorthand, to drop the Math:: part.
I guess this is just for using shorthand names?
Yes, that's to allow identifiers from some namespace to be used without the qualifier. There are two ways to do it.
Using directive: Use all names in a namespace without qualification (e.g. using namespace Math;)
Using declaration: Use only some specified names without qualification (e.g. using Math::gamma) -- this is usually better than the former.
However, both are encouraged to be used only in an implementation/source file and not in a header to avoid some sources which may have its own copy of gamma and don't want to use Math::gamma, but since you've it in the header, it'll lead a clash of the names. More details on "using namespace" in c++ headers.

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

using standard namespace in C plus plus

Consider this
#include<headerfile1>
#include<headerfile2>
.
.
#include<headerfilen>
using namespace std;
when I write this(header files are all in standard library of C++),does std namespace of all header files come into picture?
Also, if there are two libraries h1 and h2 and both have same namespace x and in those namespaces have same function func(). How do I resolve this?
From cppreference:
A using-directive that names the inline namespace is implicitly
inserted in the enclosing namespace (similar to the implicit
using-directive for the unnamed namespace).
For instance, in the following example, using namespace std::string_literals makes the operator visible inside the scope:
{ // in C++14, std::literals and its member namespaces are inline
using namespace std::string_literals; // makes visible operator""s
// from std::literals::string_literals
auto str = "abc"s;
}
If you use the using directive outside a scope (for instance as in your example), pain will follow, as the commenters stated, especially if this file is a header file: this namespace will be implicitly imported to any file that includes this one. This is why the proper way of managing a big project is to create your own namespace and put all your custom objects in that new namespace. If you really must use a using directive, do so in the implementation file, never in the header, and ideally within scopes.
This will help you avoid most conflicts, unless your namespace uses a common name:
namespace Matrix{ <--- Bad practice, Matrix will probably conflict with something
myStuff ...
}
namespace JohnsAwesomeMatrix236790{ <--- Namespace name is unique,unlikely to get conflicts.
myStuff ...
}
Also, it is much safer to import the few functions that you use instead of the entire namespace:
using namespace std; // Imports the entire namespace!
using std::cout; // Much better, we only import
using std::endl; // the names of the two functions we use a lot
Any decently written library you include will make very careful use of the using directive (if at all), so you normally don't have to worry about this. However, if you use code written with less stringent standards (e.g., scientific code) this is something to look out for.

STLPORT: What does namespace std{} mean?

In the stlport library, I saw this code:
namespace std { }
namespace __std_alias = std;
1. Are they trying to nullify the standard std namespace in the first line?
2. Why in the world would they use a longer alias name in place of the original name?
You need the namespace "in scope" before you can declare an alias to it. The empty namespace std {} informs the compiler that the namespace exists. Then they can create an alias to it.
There are reasons for creating aliases besides creating a shortcut. For example, you can define a macro to "rename" the namespace -- consider the effect of #define std STLPORT_std. Having a alias allows you to access the original namespace provided that you play the correct ordering games with header files.
No, that just makes sure the namespace's name is available in the current scope. You can open and close namespaces at any point, without affecting the contents of the namespace.
I would guess, so they could easily change their library implementation to be in a namespace other than ::std (by changing __std_alias to alias something else). This would be useful, for example, if you want to test two implementations alongside each other.
It is rather annoying to get a compiler error that there is no such namespace as std... What is the compiler thinking? Of course it exists!
Well yes it does, but as with library features, it has to be declared first. That is what the first line is doing.
With the renaming of __std_alias it allows them to give a new alias to a namespace. You may decide to do this in your own code someday.
Perhaps you want to use shared_ptr in your code but do not want to dedicate your code to using namespace boost or std. So you can create an alias, and "point" it at either boost or std. Same with other features that are in boost libraries that later became standard.
This does not tie you to using this namespace for everything as you can have more than one alias, and you can have more than one pointing to the same real namespace.
Let's say we want to call our smart pointer library sml. We can do
namespace sml = boost; // or std
in one place in the code and #include <boost/shared_ptr.hpp> from that point in the code (same header).
Everywhere else in our code we use sml::shared_ptr. If we ever switch from boost to std, just change the one header, not all your code.
In addition to what D.Shawley said, forward declaring a class that's inside a namespace requires the same syntax:
namespace std
{
template <typename T>
class vector;
}

candidate standard functions for 'using'

I knew the technique of using std::swap to enable via ADL the use of user defined swap functions, but I was not aware that this should be applied also to some other functions. For example I was writing abusively std::abs in template code wheras I should have used something like:
template <class Int> void f(Int i) {
using std::abs;
Int j = abs(i);
// ...
}
What standard function can you think of which should be used this way?
On a side note: g++ puts abs in the global namespace when including cstdlib (in fact ctsdlib includes stdlib.h (which defines the function abs) and does a #undef abs...), what does the standard says?
This is from the standard :
3.4.6 Using-directives and namespace aliases
[basic.lookup.udir]
When looking up a namespace-name in a using-directive or
namespace-alias-definition, only namespace
names are considered.
Therefore, you can use the keyword using to import variable, types and functions into the current namespace.
EDIT
You can import anything you like into the current namespace, but you should care for namespace polution, therefore try not to use using in headers, but only in the source files.
Ideally, you shouldn't be using this keyword. I use it sometimes when I have deeply nested namespaces.

What's the purpose of: "using namespace"?

There are convincing arguments against using namespace std, so why was it introduced into the language at all? Doesn't using namespace defeat the purpose of namespaces? Why would I ever want to write using namespace? Is there any problem I am not aware of that is solved elegantly by using namespace, maybe in the lines of the using std::swap idiom or something like that?
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops; or using namespace boost::assign;)
Brevity is also a strong argument. Would you really enjoy typing and reading std::placeholders::_1 instead of _1? Also, when you write code in functional style, you'll be using a myriad of objects in std and boost namespace.
Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
template <class T>
void smart_swap(T& a, T& b)
{
using std::swap;
swap(a, b);
}
If swap is overloaded for some type of T in the same namespace as T, this will use that overload. If you explicitly called std::swap instead, that overload would not be considered. For other types this falls back to std::swap.
BTW, a using declaration/directive does not defeat the purpose of namespaces, since you can always fully qualify the name in case of ambiguity.
Most of the times it is just a shortcut for writing code. You can import names into your enclosing context. I usually restrict it to .cpp files, because when you include an using directive into a .h file, it pollutes all the files in which it is included. Another good practice is restricting the using namespace to the most enclosing environment possible, for instance, inside of a method body declaration. I see it as a convenience, no more, and similar to namespace aliasing, such as:
namespace po = boost::program_options;
and then you can write
po::variables_map ...
The main reason why using namespace was introduced was backwards compatibility: If you have lots of pre-namespace code using lots of (pre-standard versions of) standard library functions and classes, you want a simple way to make that code work with a standard conforming compiler.
BTW, the argument dependent lookup rules at least for C++98 mean that using namespace std::rel_ops will not do what you want in templates (I don't know if this changed in a later version of the standard).
Example:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
}
using namespace std::rel_ops;
int main()
{
X x;
bar(x); // won't work: X does not have operator>
}
Note that putting the using namespace in namespace foo won't help either.
However, using declarations in the right spot help:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
using std::rel_ops::operator>;
}
int main()
{
X x;
bar(x); // now works: operator> found per ADL via the using declaration in `namespace foo`
}
People specifically object to using namespace std; but not to using namespace BigCorp; or to referring to std::cout (which is using the namespace, just not using it, if you know what I mean.) Also, most of the objections to using namespace std are in a header file. In a source file, where the effects can be immediately seen, it's less harmful.
Namespaces are an incredibly useful concept that allow me to have a class called Date even though a library I'm using has a class called Date. Before they were added to the language, we had to have things like GCDate and GCString (my company, Gregory Consulting, predates std::string). Making use of namespaces (with or without the using keyword) lets us all write cleaner, neater code. But when you have to say Gregcons::string every time, you kind of lose the cleaner, neater part. [Disclaimer: I don't actually use my own string class anymore - imagine some appropriate name conflict.] That's the appeal of the using statement. Keep it out of headers, don't apply it to std, and you should generally stay out of trouble.
I find it useful when working with libraries with deeply nested namespaces. The Boost library is one such example. Imaging typing boost::numeric::ublas::matrix<double> m all over the place ...
The thing to avoid is doing using namespace in a header file as this has the potential for royally screwing up any program that includes said header. Always place using namespace statements in .cpp/.cxx files, so that it's restricted to file scope.
"Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace"
More information here:
http://www.cplusplus.com/doc/tutorial/namespaces/