For example, initially I have a sample program:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int a[3];
sort(begin(a),end(a));
cin;
}
Now I want to modifystd::cin
(to provide more functions like invoke a function when input fails). So I introduces a headermystd.h
like:
#include<iostream>
#include<algorithm>
//begin of mystd.h
namespace mystd {
struct cin_wrapper {
}cin;
}
//end of mystd.h
using namespace std;
int main() {
int a[3];
sort(begin(a),end(a));
mystd::cin;
}
But the change seems to be not convenient.(Users must mention all components using std::sort;using mystd::cin;
or replace all cin
with mystd::cin
. using namespace std;using mystd::cin;
causes the cin
ambiguous)
In fact I'm going to write a modified standard library and make the use of it as convenient as the original one. The ideal code I wish users can write is:
(PS: this means mystd
can be just used as std
, not indicates I want to encourage users to use using namespace
everywhere)
#include<iostream>
#include<algorithm>
#include "mystd.h"
using namespace mystd;
int main() {
int a[3];
sort(begin(a),end(a));//std::sort
cin;//mystd::cin
}
//or
int main() {
int a[3];
mystd::sort(mystd::begin(a),mystd::end(a));//sort, begin, end from std
mystd::cin;
}
I've tried to add using namespace std;
in mystd
but it also causes ambiguity.
One complicated solution I can image is to create a using statement like using std::string;
in mystd
for all std members not modified.
Is there a more practical way for me to implement mystd.h
?
A namespace can contain variables, functions, classes or other objects and even another namespace. Each member of the namespace can be referred to using a namespace space.
Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes. Save this answer.
The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.
It is considered "bad" only when used globally. Because: You clutter the namespace you are programming in. Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz; .
If you really insist on doing this, you can manage to do so by introducing your using
statements at nested scopes. For example:
using namespace std;
int main() {
using namespace mystd;
int a[3];
sort(begin(a), end(a));//std::sort
cin_wrapper w;//mystd::cin
}
Anything involving using namespace std;
should be avoided though (using other, more restricted namespaces isn't so bad, but that one is a huge truckload of cans of worms you're opening).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With