If name in C++ is not fully qualified, e.g. std::cout, it can lead to an unintentional error, such as mentioned at https://en.cppreference.com/w/cpp/language/qualified_lookup. But using a fully qualified name for ::std namespace, e.q. ::std::cout, is very rare, as I have noticed.
Is there any reason why a fully qualified name for ::std namespace is not used?
And what about using fully qualified name for own created namespaces? Is it good idea?
You are completely right, in the sense that yyyy::xxx can be ambiguous if there is a namespace yyyy and also a class yyyy which are both visible in the same scope. In this case only the full qualification ::yyyy::xxx can solve the ambiguity. The example of your link makes it very clear:
// from cppreference.com
#include <iostream>
int main() {
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
But in practice, it's difficult to create a conflicting std at top level, since most of the includes from the standard library will make it fail:
#include <iostream>
struct std { // OUCH: error: ‘struct std’ redeclared as different kind of symbol
int hello;
};
This means that to create a conflict, you'd need to define local classes or introduce a using clause in another namespace. In addition, nobody will (dare to) call a class std.
Finally, in practice, ::yyyy::xxx is less convenient to read. All this explains why you won't find it very often.
Additional remark
The problem is not so much for std which is well known, but rather for your own namespaces and third party libraries. In this case, the namespace alias would be a better alternative to :::yyyy to disambiguate:
namespace foo {
void printf() { }
}
int main() {
foo::printf(); // ok, namespace is chose because no ambiguity
struct foo {/*...*/ }; // creates ambiguity
//foo::printf(); // error because struct foo is chosen by name lookup
::foo::printf(); // ok, but not if you decide to move the code to be nested in another namespace
namespace mylib = foo ; // or ::foo (see discussion below)
mylib::printf(); // full flexibility :-)
}
Its advantage is a higher flexibility. Suppose for example that you'd move your code to nest it in an enclosing namespace. With the namespace alias, your code could continue to work as is (in the worst case with a minor adjustment in the alias definition). With the global scope resolution, you'd have to change all the statements where the global namespace ::foo would be used.
To maintain big code or better readability or clashes in names, C++ has provided namespace " a declarative region".
A namespace definition can appear only at global scope, or nested within another namespace.
#Sample Code
#include <iostream>
int main()
{
struct std{};
std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
::std::cout << "ok\n"; // OK: ::std finds the namespace std
}
In the above code compiler is looking for cout in struct std , but in next line when you use ::std::cout it looks for cout in globally defined std class.
Solution:
#include <iostream>
//using namespace std; // using keyword allows you to import an entire namespace at once.
namespace test
{
void cout(std::string str)
{
::std::cout<<str;
}
}
int main()
{
cout("Hello");//'cout' was not declared in this scope
::test::cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}
Or use the in this way , it is just for better readability
##
using namespace test;
int main()
{
cout("Hello");//'cout' was not declared in this scope
cout("Helloo ") ;
::std::cout<<"it is also ok\n";
}
Related
This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.
Under some situations, it seems like I can access functions that should be in the std namespace without a using or std:: qualifier. So far, I've only seen this occur with functions from the algorithm library.
In the following example, I expect all_of() to be in the std namespace, but this code compiles without error in VS2013 (Microsoft Compiler 18).
#include <iostream>
#include <string>
#include <algorithm>
int main() {
const std::string text = "hey";
std::cout << all_of(begin(text),end(text),islower);
return 0;
}
Changing std::cout to cout without adding a using namespace std or using std::cout generates an "undeclared identifier" error as expected.
What's going on here?
This probably happens due to Argument-Dependent Lookup. The iterator returned by begin(text) and end(text) is probably a class defined in namespace std (or nested in a class in namespace std), which makes namespace std associated with it. Looking up unqualified names for function calls looks into associated namespaces, and finds all_of there.
By the way, this is exactly the same reason why calling begin(text) works, even though the function template begin() is defined in namespace std. text is a std::basic_string, so std is searched.
I am taking a programming class in school and I wanted to start doing some c++ programming out of class. My school using Microsoft Visual C++ 6.0 (which is from 1998) so it still uses <iostream.h> rather than <iostream> and using namespace std. When I started working, I couldn't figure out how and when to use using namespace std and when to just use things like std::cout<<"Hello World!"<<'\n'; (for example) as well as it's limits and other uses for the namespace keyword. In particular, if I want to make a program with iostream and iomanip, do I have to state "using namespace std" twice, or is there something different that I would have to use as well, or can I just do the same thing as I did with iostream? I tried googling it but I didn't really understand anything. Thanks in advance for the help.
Ok, handful of things there, but it is manageable.
First off, the difference between:
using namespace std;
...
cout << "Something" << endl;
And using
std::cout << "Something" << std::endl;
Is simply a matter of scope. Scope is just a fancy way of saying how the compiler recognizes names of variables and functions, among other things. A namespace does nothing more than add an extra layer of scope onto all variables within that namespace. When you type using namespace std, you are taking everything inside of the namespace std and moving it to the global scope, so that you can use the shorter cout instead of the more fully-qualified std::cout.
One thing to understand about namespaces is that they stretch across files. Both <iostream> and <iomanip> use the namespace std. Therefore, if you include both, then the declaration of using namespace std will operate on both files, and all symbols in both files will be moved to the global scope of your program (or a function's scope, if you used it inside a function).
There are going to be people who tell you "don't use using namespace std!!!!", but they rarely tell you why. Lets say that I have the following program, where all I am trying to do is define two integers and print them out:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
cout << cout << endl << endl; // The compiler WILL freak out at this :)
return 0;
}
When I use using namespace std, I am opening the door for naming collisions. If I (by random chance), have named a variable to be the same thing as what was defined in a header, then your program will break, and you will have a tough time figuring out why.
I can write the same program as before (but get it to work) by not using the statement using namespace std:
#include <iostream>
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
std::cout << cout << endl << std::endl; // Compiler is happy, so I'm happy :)
return 0;
}
Hopefully this has clarified a few things.
If you use the header names without the .h, then the stuff declared/defined in it will be in the std namespace. You only have to use using namespace std; once in the scope where you want stuff imported in order to get everything; more than one using namespace std; doesn't help anything.
I'd recommend against using namespace std; in general, though. I prefer to say, for example, using std::cout; instead, in order to keep names in std from conflicting with mine.
For example:
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
may cause mysterious issues, because left and right exist in the std namespace (as IO manipulators), and they get imported if you lazily say using namespace std;. If you meant to actually use the IO manipulators rather than output the variables, you may be a bit disappointed. But the intent isn't obvious either way. Maybe you just forgot you have ints named left and right.
Instead, if you say
#include <iostream>
#include <iomanip>
int main()
{
using std::cout;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
or
#include <iostream>
#include <iomanip>
int main()
{
int left = 1, right = 2;
std::cout << left << " to " << right << "\n";
}
everything works as expected. Plus, you get to see what you're actually using (which, in this case, includes nothing from <iomanip>), so it's easier to keep your includes trimmed down to just what you need.
Here is a good link that describes namespaces and how they work.
Both methods are correct, that is, you can either introduce a namespace with the "using" statement or you can qualify all the members of the namespace. Its a matter of coding style. I prefer qualifying with namespaces because it makes it clear to the reader in which namespace the function / class is defined.
Also, you do not have to introduce a namespace twice if you are including multiple files. One using statement is enough.
Good question, Ryan. What using namespace does is importing all symbols from a given namespace (scope) into the scope where it was used. For example, you can do the following:
namespace A {
struct foo {};
}
namespace B {
using namespace A;
struct bar : foo {};
}
In the above examples, all symbols in namespace A become visible in namespace B, like they were declared there.
This import has affect only for a given translation unit. So, for example, when in your implementation file (i.e. .cpp) you do using namespace std;, you basically import all symbols from std namespace into a global scope.
You can also import certain symbols rather than everything, for example:
using std::cout;
using std::endl;
You can do that in global scope, namespace scope or function scope, like this:
int main ()
{
using namespace std;
}
It is up to a programmer to decide when to use fully qualified names and when to use using keyword. Usually, it is a very bad taste to put using into a header files. Professional C++ programmers almost never do that, unless that is necessary to work around some issue or they are 100% sure it will not mess up type resolution for whoever use that header.
Inside the source file, however (nobody includes source files), it is OK to do any sort of using statements as long as there are no conflicting names in different namespaces. It is only a matter of taste. For example, if there are tons of symbols from different namespaces being used all over the code, I'd prefer at least some hints as for where they are actully declared. But everyone is familiar with STL, so using namespace std; should never do any harm.
There also could be some long namespaces, and namespace aliasing comes handy in those cases. For example, there is a Boost.Filesystem library that puts all of its symbols in boost::filesystem namespace. Using that namespace would be too much, so people usually do something like this:
namespace fs = boost::filesystem;
fs::foo ();
fs::bar ();
Also, it is almost OK to use namespace aliasing in headers, like this:
namespace MyLib {
namespace fs = boost::filesystem;
}
.. and benefit from less typing. What happens is that users that will use this header, will not import the whole filesystem library by saying using namespace MyLib;. But then, they will import "fs" namespace from your library that could conflict with something else. So it is better not to do it, but if you want it too badly, it is better than saying using namespace boost::filesystem there.
So getting back to your question. If you write a library using C++ I/O streams, it is better not to have any using statements in headers, and I'd go with using namespace std; in every cpp file. For example:
somefile.hpp:
namespace mylib {
class myfile : public std::fstream {
public:
myfile (const char *path);
// ...
};
}
somefile.cpp:
#include "somefile.hpp"
using namespace std;
using namespace mylib;
myfile::myfile (const char *path) : fstream (path)
{
// ...
}
Specific to using namespace std
You really shouldn't ever use it in a header file. By doing so, you've imported the entire 'std' into the global namespace for anyone who includes your header file, or for anyone else that includes a file that includes your file.
Using it inside a .cpp file, that's personal preference. I typically do not import the entire std into the global namespace, but there doesn't appear to be any harm in doing it yourself, to save a bit of typing.
Anyone can help me to understand this statement found in chapter 3 (Library Types) by Stanley Lipmann?
"Using an unqualified version of a namespace name without a using declaration is an error, although some compilers may fail to detect this error"
I'm having such hard time understanding the semantics of his sentence (english).
Is he trying to say something like the below scenario?
int main() {
xx::yy
}
where xx is a namespace not defined using the "using" statement and yy is a member?
Example:
cout is a name of the std namespace. The unqualified name is cout. The qualified name is std::cout. It is an error to use the unqualified name(cout) without a using declaration beforehand. You can use either one of the two following declarations:
// This brings in the entire std namespace
using namespace std;
OR
// This only brings in cout. You would still need to qualify other names,
// such as cin, endl, etc...
using std::cout;
What he's saying is that the following code should not compile:
#include <iostream>
void foo() {
cout << "This is an error!" << endl;
}
The cout and endl names are not defined right now. They're declared as std::cout and std::endl, and in order to use them, you can do one of a few things:
#include <iostream>
void foo() {
std::cout << "This, I think, is the best way to do it." << std::endl;
}
Using the fully qualified name prevents collisions later on: you'll never have something else called std::cout.
#include <iostream>
void foo() {
using std::cout;
using std::endl;
cout << "This is pretty good." << endl;
}
Having the using statements specify the exact names you're using, and having the using statements in the function, can save some typing and makes collisions pretty unlikely.
#include <iostream>
using namespace std;
void foo() {
cout << "This works, but isn't good." << endl;
}
Importing the entire std namespace makes it pretty likely that you'll end up having a function named the same as an std function.. You might discover that as soon as you write it, or you might write your function and then later include the header file with the std version of the function, at which point your application will mysteriously break.
A namespace name is the name of a namespace.
namespace A {
}
namespace B = A;
The statement says that using a namespace name without a using declaration is an error. But that's not true: The above code is fine, still using the namespace-name A as an unqualified name.
Probably it should say the following, to convey its meaning
"Using an unqualified version of a namespace member name without a using declaration
outside the scope of the namespace is an error, although some compilers may fail to
detect this error"
Mentioning the scope is important. The following, for example, is fine too, even though it uses the unqualified version of a namespace member name
namespace A {
int x;
int &y = x; // x is an unqualified name
}
Books should be careful to try and not use slippery language. And even outside the scope of the namespace, the above sentence is not entirely correct because you can also extend the scope of x by a using directive. Using declarations aren't the only way to name a namespace member outside the namespace using an unqualified name.
I'm a beginner in programming and I often see many programs using the prefix std if they are using any std functions like std::cout, std::cin, etc. I was wondering what is it's purpose ? Is it just a way of good programming or is there more to it ? Does it make any difference for the compiler or is it readability or what ? Thanks.
The STL types and functions are defined in the namespace named std. The std:: prefix is used to use the types without fully including the std namespace.
Option 1 (use the prefix)
#include <iostream>
void Example() {
std::cout << "Hello World" << std::endl;
}
Option #2 (use the namespace)
#include <iostream>
using namespace std;
void Example() {
cout << "Hello World" << endl;
}
Option #3 (use types individually)
#include <iostream>
using std::cout;
using std::endl;
void Example() {
cout << "Hello World" << endl;
}
Note: There are other implications to including an entire C++ namespace (option #2) other than not having to prefix every type / method with std:: (especially if done within a header) file. Many C++ programmers avoid this practice and prefer #1 or #3.
C++ has a concept of namespaces.
namespace foo {
int bar();
}
namespace baz {
int bar();
}
These two functions can coexist without conflict, since they're in different namespaces.
Most of the standard library functions and classes live in the "std" namespace. To access e.g. cout, you need to do one of the following, in order of preference:
std::cout << 1;
using std::cout; cout << 1;
using namespace std; cout << 1;
The reason you should avoid using is demonstrated with the above foo and baz namespaces. If you had using namespace foo; using namespace baz; any attempt to call bar() would be ambiguous. Using the namespace prefix is explicit and exact, and a good habit.
Nobody mentioned in their answer that a using namespace foo statement can be put inside a function body, thereby reducing namespace contamination in other scopes.
For example:
// This scope not affected by using namespace statement below.
void printRecord(...)
{
using namespace std;
// Frequent use of std::cout, io manipulators, etc...
// Constantly prefixing with std:: would be tedious here.
}
class Foo
{
// This scope not affected by using namespace statement above.
};
int main()
{
// This scope not affected either.
}
You can even put a using namespace foo statement inside a local scope (pair of curly braces).
It's a C++ feature called namespaces:
namespace foo {
void a();
}
// ...
foo::a();
// or:
using namespace foo;
a(); // only works if there is only one definition of `a` in both `foo` and global scope!
The advantage is, that there may be multiple functions named a - as long as they are within different namespaces, they can be used unambiguously (i.e. foo::a(), another_namespace::a()). The whole C++ standard library resides in std for this purpose.
Use using namespace std; to avoid the prefix if you can stand the disadvantages (name clashes, less clear where a function belongs to, ...).
It's short for the standard namespace.
You could use:
using namespace std
if you don't want to keep using std::cout and just use cout