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.
Related
Unfortunately I'm bound to using a thirdparty macro which assumes that I am within the namespace thirdparty. However this macro declares some types which I need to be outside of the thirdparty namespace, so I can't use this snippet:
namespace thirdparty
{
TP_MACRO(my_type_name, inner);
}
If I did, all of my declared types would be in the thirdparty:: namespace which won't work.
The issue is that the TP_MACRO is using types from inside of the thirdparty namespace without qualifying them. To get arround the this I am currently bringing these types into the current scope with using declarations:
using thirdparty::type1;
using thirdparty::type2;
TP_MACRO(my_type_name, inner);
The downside of this approach is that I'm polluting the global namespace with these types, which is generally bad practice (this code is in a header file).
I can wrap the above snippet in a new namespace (which I am doing), but I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?
The TP_MACRO is similar to (but is more complex in reality):
#define TP_MACRO (name, inner) \
typedef type1<inner> type1_##name; \
typedef type2<inner> type2_##name;
It is also subject to change, hence why I would avoid copying it's contents.
Try declaring the types in an embedded namespace inside thirdparty so that the macro is happy, then alias that namespace so that it's accessible globally:
namespace thirdparty::myns {
TP_MACRO(my_type_name, inner);
}
namespace myns = thirdparty::myns;
If you are not using C++17, then use:
namespace thirdparty {
namespace myns {
TP_MACRO(my_type_name, inner);
}
}
I can wrap the above snippet in a new namespace (which I am doing)
That's what you should be doing.
I would like to know if there is a way to scope these using declarations so that after the macro has declared my types, I can remove them from the surrounding namespace?
No.
Also I suggest making a recommendation upstream that they improve these macros.
This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 7 years ago.
Two ways to use the using declaration are
using std::string;
using std::vector;
or
using namespace std;
which way is better?
It depends.
If you want to inject a single name into another scope, the using-declaration is better, e.g.
namespace foolib
{
// allow vector to be used unqualified within foo,
// or used as foo::vector
using std::vector;
vector<int> vec();
template<typename T> struct Bar { T t; };
template<typename T>
void swap(Bar<T>& lhs, Bar<T>& rhs)
{
using std::swap;
// find swap by ADL, otherwise use std::swap
swap(lhs.t, rhs.t);
}
}
But sometimes you just want all names, which is what a using-directive does. That could be used locally in a function, or globally in a source file.
Putting using namespace outside a function body should only be done where you know exactly what's being included so it's safe (i.e. not in a header, where you don't know what's going to be included before or after that header) although many people still frown on this usage (read the answers at Why is "using namespace std" considered bad practice? for details):
#include <vector>
#include <iostream>
#include "foolib.h"
using namespace foo; // only AFTER all headers
Bar<int> b;
A good reason to use a using-directive is where the namespace only contains a small number of names that are kept intentionally segregated, and are designed to be used by using-directive:
#include <string>
// make user-defined literals usable without qualification,
// without bringing in everything else in namespace std.
using namespace std::string_literals;
auto s = "Hello, world!"s;
So there is no single answer that can say one is universally better than the other, they have different uses and each is better in different contexts.
Regarding the first usage of using namespace, the creator of C++, Bjarne Stroustrup, has this to say in §14.2.3 of The C++ Programming Language, 4th Ed (emphasis mine):
Often we like to use every name from a namespace without qualification. That can be achieved by providing a using-declaration for each name from the namespace, but that's tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use a using-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using a using-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book. [...]
Within a function, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful with using-directives in the global scope. In particular, don't place a using-directive in the global scope in a header file except in very specialized circumstances (e.g. to aid transition) because you never know where a header might be #included.
To me this seems far better advice than just insisting it is bad and should not be used.
using std::string; and using std::vector;.
Polluting the global namespace with a bunch of symbols is a bad idea. You should just use the std namespace prefix too, so you know that you're using standard library containers. Which is better than both options IMO.
If you are simply using the standard library and nothing else and never will be adding in any other libraries to your project, by all means, use using namespace std; - Whatever you feel more comfortable with in that situation. The convention of "never use using namespace std;" comes from the fact that multiple other libraries define things such as string, vector and such. It is good practice to never import the whole namespace, but it should cause no bothers in your case.
I use cocos2dx. When I use classes from it I need to type cocos2d:: very often unless I type using namespace cocos2d;.
How can I avoid having to repeat the namespace all the time?
There are several ways to use stuff from other namespaces without having to repeat the namespace on every instance.
Import the entire namespace: using namespace cocos2d; You can now use all members of that namespace by only their name without the namespace prefix. This pollutes your own namespace with possibly quite a few names (depending on the contents of the imported namespace) which might not be desirable.
Import single names from that namespace: using cocos2d::MyClassName; This only imports the given name. The upside is that your namespace is not polluted. The downside is that you will have to do it for every namespace member you want to import. If you only need a few then this approach is fine.
Create a namespace alias: namespace co = cocos2d; Now you can refer to members of the cocos2d namespace as if they were members of the co namespace.
Create a type alias (since C++11): using CoClass = cocos2d::MyClassName; You can then refer to the aliased member with the identifier you chose. This can be especially helpful when an imported type shadows a type in your own namespace.
Chris's answer is correct and complete, but I would add that it's a better idea to explicitly specify every member's namespace to avoid ambiguity in other files that included your header file.
using namespace cocos2d; will implicitly use that namespace in every file that includes your header. You may put it inside the .cpp file. Same thing goes for using cocos2d::MyClassName; and namespace aliases.
Those will all work, but you shouldn't use them.
See that answer to the question: “using namespace” in c++ headers
It's considered bad practice to employ using namespace in C++ headers. Is it similarly a bad idea to use namespace aliasing in a header, and each implementation file should declare the aliases it wishes to use?
Since headers are the places you tend to use fully specified names (since we don't use namespaces in headers), aliases would be useful but they would still propagate though your source when #included.
What is the best practice here? And what is the scope of a namespace alias?
If you put a namespace alias into your header this alias will become part of your (public) API.
Sometimes this technique is used to do ABI compatible versioning (or at least to make breakage visible) like this:
namespace lib_v1 { ... }
namespace lib_v2 { ... }
namespace lib = lib_v2;
or more commonly:
namespace lib {
namespace v1 {}
namespace v2 {}
using namespace v2;
}
On the other hand if you do it just to save some typing it is probably not such a good idea.
(Still much better than using a using directive)
I do it with unnamed namespaces this way:
#include <whatyouneed>
...
namespace {
typedef ...
using ..
namespace x = ...
// anything you need in header but shouldn't be linked with original name
}
// normal interface
class a: public x::...
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;
}