I am trying to understand namespaces in C++. I read that there are two ways of accessing namespace variables and functions. First one is to write using :: and second one is by using using directive at the top and not writing it again and again. I realized that the first method is better as the second one may lead to conflicts.
But, I want to know how actually 2nd method is working. For Example, If I write using namespace std at the top, how does the compiler know for which functions it has to add std:: in the beginning and for which ones it has no to. If I have written a function in main, firstly it will check in my main file for the function and then it will check in the header files ( that I have declared at top of main file) for the function declaration. Now, according to my understanding the functions in std are declared inside namespaces. So, I will not find it if I search without using ::.
So, when will std:: will get add at the beginning of a function?
(This is simplified, but it's the general gist of it.)
When you write std::bar, the compiler doesn't look for something named "std::bar", it looks for something named "bar" inside the "std" namespace.
using namespace std; makes the compiler look up names in both the current namespace and in std, so it doesn't need to add "std::" anywhere in order to look for "std::bar" - it will be found by looking for "bar" inside std as well as in the current namespace.
Here's a link to a description of how this works: http://en.cppreference.com/w/cpp/language/unqualified_lookup.
A more general overview starts here(http://en.cppreference.com/w/cpp/language/lookup) and shows you all the cases when you have qualified names vs unqualified names.
Note that name resolution in C++ is actually quite complex. Argument Dependant Lookup (ADL) http://en.cppreference.com/w/cpp/language/adl can also apply when looking up where the function declaration is.
Also the compiler may need to do overload resolution as there can be multiple functions but with differing numbers of arguments and these overloads may exist in different namespaces.
Related
When using a header which has a format <cname>, an implementation will put names into std namespace. And it may put names into the global namespace as well, as it is described here:
[ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. [...] — end example ]
Is there a (maybe compiler dependent) way to circumvent/disable this behavior (I'm open to any tricky solution)? I'd like to use names from std only, and I'd like to have an error/warning when using names from the global namespace:
#include <cmath>
double a = cos(0.5); // I'd like to have an error here, because std:: is missing
The reasons:
It is hard to write a portable code, if it may use names from the global namespace, as these names may be not available in other compilers. It is much cleaner to use everything from std, and not use the global namespace at all
cos(0.5f) does a different thing whether std:: is prefixed or not (float vs double result).
Since tricky solutions are fine...
Use a C++ parser, e.g. Clang, and write a tool that parses the header file, collects all the function definitions, and then compares that set against all definitions and calls to global functions.
Of course, it will also pick up cases where someone has defined or called a function with the same name as the standard ones, but you will probably want to avoid that as well anyway.
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.)
E.g. SFML::Render() vs SFML_Render()
I've noticed in libraries that offer C and C++ bindings, that often the C++ versions make use of namespaces (SFML, libtcod) and the C bindings do the same thing but just prefix the name with what library they belong to.
Both of them require the programmer to prefix the function, both give context as to where they belong, both of them perform the same function. I'm really confused as to what benefits namespaces offer over function prefixing.
using-declarations
You can write using SFML::Render after which you can simply call the function with Render(), without needing the SFML:: in the front. The using-declaration can also be scoped to a function or class. This is not possible with prefixed names.
using-directives
You can also bring a whole namespace to the current scope with using namespace. Everyone knows what using namespace std does. These can also be scoped.
Namespace aliases
If you have a symbol with a long qualified name e.g. mylib::sublib::foo::bar::x, you can write namespace baz = mylib::sublib::foo::bar and then refer to x with just baz::x. These are scope-specific as well.
Among the C-style prefixed names there's usually nothing that big that would need an alias, and if there were you could just use a macro.
Adding to & removing from a namespace
If you have a file full of functions that need to be placed under a namespace x you can simply add two lines to make it happen: namespace x { and }. Removing from a namespace is equally simple. With prefixed names you have to manually rename each function.
Argument-dependent lookup
You may be able to omit the namespace qualification on a function call if the function lives in the same namespace as some of its arguments. For example, if namespace baz contains both an enum E and a function F that takes it, you can write F(baz::E) instead of baz::F(baz::E). This can be handy if you follow the style that prefers namespaced free functions over methods.
So in conclusion, namespaces are more flexible and offer more possibilities than the prefixed naming style.
SFML_Render is easy to find with fgrep -w SFML_Render, whereas SFML::Render may appear in some source files as just Render if the SFML namespace is implicit.
If you program in C++, there are strong benefits in using the C++ constructs, but you better use a powerful environment such as Eclipse or Visual Studio to help you make sense of all the added complexities.
If you want interoperability with C, you should not use namespaces nor overloading.
they way i see it there are severel uses for namespaces.
some of them:
Name isolation: define a package (a set of classes, functions,
globals, type definitions, etc.) in a namespace to ensure that when
included, these names do not conflict with existing code.
Version control: maintain multiple versions of the code.
and offcourse : A using statement can be used to make names available
without the :: scope operator
Ideally, namespaces should
• Express a logical coherent set of features
• Prevent user access to unrelated features.
• Impose minimal notational burden on users.
I'm wondering a bit about the namespace and using in C++ basically I would like to know the differences and figure out how to use it in the best way.
As I see it there are (at least) three ways to resolve a class name and I am not sure how to choose among them:
using namespace <namespace>
using <namespace>::<what_to_use>
<namespace>::<what_to_use> <use_it>
I would like to know the advantages especially if there are performance involved in one or the other way, if it's just syntactical and a matter of preference or if there are other things I haven't considered regarding this.
First is an using namespace directive, it brings all the symbol names from the specified namespace in your current namespace, irrespective of whether you need/use them. Certainly undesirable.
Second is using namespace declaration. It only brings the specified symbol name in your current namespace. Advantage is you don't have to type the fully qualified name everytime.
Third is an fully qualified names of the symbol. Disadvantage is that you have to type the fully qualified name everywhere you use the symbol.
Clearly, Second & Third are the more suitable ones. There is no performance difference in either of them. The only difference is the amount of characters you type in. Simply, choose either depending on what your coding standard specifies.
EDIT:
As #Jerry points out, using declaration in combination with ADL(Argument dependent lookup) can lead to undesirable effects.
You can find a detailed explanation in one of my answers:
Detailed explanation on how Koenig lookup works with namespaces and why its a good thing?
under the section,
Why the criticism of Koenig Algorithm?
There is one (admittedly, somewhat uncommon) situation in which the form you use really can make a difference, and the form you want to use is using namespace foo, and it's most commonly applied to the std namespace (i.e., where you write using namespace std;.
The most obvious example is that you're writing a sort for a user-defined type. It's possible that this will be applied to a type for which the user has also defined their own swap.
You're stuck with a situation where you want to use their swap if they've defined one, but use std::swap if they haven't defined one. If you use std::swap directly in your code, then you'll end up using std::swap even if the type has a swap of its own defined. Conversely, your code will fail to compile if you directly specify a swap specifically for the type, and none has been supplied.
To get around this, you do something like:
using namespace std;
template <class Iter>
void my_sort(Iter first, Iter last) {
// ...
if (*last < *first)
swap(*first, *last);
}
This will find the swap specifically for the type being compared (i.e., a swap defined in the same namespace as that type), if there is one (via argument dependent lookup), and std::swap if none is defined for the type (via the using namespace std;).
This can have an impact on performance -- if they've written a swap specifically for their type, you can generally expect that it's because by doing so, they can provide better performance. That means that explicitly specifying std::swap may work, but will probably lead to inferior performance.
Otherwise, it's almost entirely a matter of convenience and readability -- I mostly prefer giving the full names (e.g., std::swap) except in a situation like above, where (at the time that I'm writing the code) either of at least two possibilities might be preferred, and I want to give the compiler sufficient leeway to pick the right one.
The other time I find using declarations/directives useful is when namespaces get really deeply nested. Boost (for one obvious example) has some names that would be way too long for convenient use if you used the fully qualified name every time. This was especially true for the (now, thankfully, mostly obsolete) Boost Lambda library, where you used placeholders like _1, that would have ended up as something like boost::lambda::placeholders::_1 (but I'm going from memory, so that's probably at least partly wrong) if you insisted on using a fully qualified name. That would have defeated a large part of the purpose of using the lambda library in the first place.
There's no performance gain or penalty whatsoever. All calls and variables are resolved at compile-time.
The choice between the three is somewhat subjective. Yes, using namespace <ns>; is sometimes frowned upon for polluting the global namespace, but I think it's safe to use for small files.
I tend to use the second one for testing purposes where I'm expecting conflicts, but I'd just remove it afterwards. This can get messier because you can end up with combinations of both qualified and un-qualified names:
vector<std::string> x;
because you have a using std::vector; at the top, but not a using std::string;.
I preffer the third.
There is zero impact on performance of your code, this is purely a compile-time thing. It might (in theory) have some impact on compilation times, but I doubt that would ever reach measurable proportions.
using namespace std (or any other namespace for that matter) is definitely to be avoided in header files, which can be included anywhere and introducing the symbols in them could result in ambiguities.
Generally, namespaces exist to avoid name clashes and using namespace destroys this purpose. So does using the_namespace::some_id, to a lesser degree. There is no definite answer to your question, but I generally follow these rules:
Never put using namespace in a header file.
Avoid using namespace and using, unless it can save tremendous amounts of typing. Use namespace aliases if necessary (that is, namespace abbrv = some_really::long_and::nested_namespace;).
Try to limit the scope of using: you can put this into functions and blocks as well as namespace scope. That is, if you have a logging function in your .cpp file, put using std::cout; and using std::endl; (or whatever you're using) into the function body, not into the file scope.
Main reason is that it could lead to ambiguities (both for compiler and for human reader) and it can also slowdown the compilation itself (but that's not that big problem as the first thing)
I am using two large libraries (GUI & network) and I can happily do
using namespace FirstLib;
using namespace SecondLib;
Except for 1 single class called Foobar where names clash.
I my code, I do not use FirstLib::Foobar. Is there a way to say "in my code, whenever you see Foobar, think SecondLib::Foobar ?
using namespace is evil! Namespaces were made to prevent such problems as you have! But that said, try:
using namespace FirstLib;
using namespace SecondLib;
using SecondLib::Foobar;
or even (for some compilers):
using namespace FirstLib;
using namespace SecondLib;
typedef SecondLib::Foobar Foobar;
It's strange nobody suggested to replace the full namespace use by the list of used class names. This solution is even in the C++faq (where I should have thought to look first).
If we cannot say
include all FirstLib, but remove SecondLib::Foobar
We can use using-declarations of the exact elements we need:
using FirstLib::Boids;
using FirstLib::Life;
// no using FirstLib::Foobar...
You've basically answered your own question. You must explicitly say which class you want to use, so you must do SecondLib::Foobar whenever you use that class.
You have to pick one of these namespaces and get rid of the 'using', and explicitly call out all the class names. C# has a way around this, but C++ does not afaik...
I don't think there's a way of excluding names. You either bring in the whole lot, or each one individually. Even when you bring in the whole lot, you can always disambiguate conflicting names by qualifying them fully.
However, you could use typedef to rename the offending class:
typedef Lib2::FooBar FooBaz;
And I guess, with a conflicting function, you could use a function pointer to "rename" the conflicting one.
I guess it's kind of a non-solution. I can understand the occasional motivation to use using declarations - sometimes there are indeed many different names that you'll use all over the place - but if just one is conflicting: be explicit. It would be confusing to anyone familiar with the libraries anyway, seeing that both namespaces are imported.
Also, using declarations respect scope: you can make one namespace visible in one function, but not the other namespace - assuming you don't even use it in that function.
Have you tried:
using SecondLib::Foobar;
?
If you load all elements from both namespace to current scope by use of using namespace directove:
using namespace FirstLib;
using namespace SecondLib;
and there is potential that some of the names in those namespace may clash, then you need to tell compiler explicitly which of the element you want to use, in current scope, by use of using declaration:
using SecondLib::Foobar;
As the C++ standard says:
7.3.3 The using declaration
1 A using-declaration introduces a
name into the declarative region in
which the using-declaration appears.
That name is a synonym for the name of
some entity declared elsewhere.
This line requests compiler to think SecondLib::Foobar whenever it sees Foobar for the rest of current scope in which the using declaration was used.
The using directive and declaration is very helpful, but they may cause problems as the one you're dealing with. So, it's a good idea to narrow use of any form of using to minimal scope possible. You can use the directive using namespace in scope of other namespace
namespace MyApp {
using namespace ::SecondLib;
}
or even a function. The same applies to using declaration. So, it's a good idea to narrow the scope of use of any of them:
void foo()
{
::SecondLib::Foobar fb;
}
It may seem tedious, but it is only when you type, though you most likely use intellisense-enabled editor, so cost is really small, but benefits are large - no confusions, readable code, no compilation issues.
It's also a very good idea to NOT to use using namespace in header scope. See Header files usage - Best practices - C++
My own tip: do use full qualification whenever you need to use any of these types