例如,最初我有一个示例程序:
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int a[3];
sort(begin(a),end(a));
cin;
}
Run Code Online (Sandbox Code Playgroud)
现在我想修改std::cin(提供更多函数,如输入失败时调用函数).所以我介绍了一个标题mystd.h:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但变化似乎不太方便.(用户必须提及的所有组件using std::sort;using mystd::cin;或更换所有cin有mystd::cin.using namespace std;using mystd::cin;引起cin歧义)
事实上,我将编写一个经过修改的标准库,并使其像原始库一样方便.我希望用户可以编写的理想代码是:
(PS:这意味着mystd可以只用作std,而不是表示我想鼓励用户using namespace到处使用)
#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;
}
Run Code Online (Sandbox Code Playgroud)
我试图添加using namespace std;,mystd但它也导致歧义.
一个复杂的解决方案,我可以形象是创建一个using语句就像using std::string;在mystd所有性病成员不会被修改.
我有更实际的方法来实施mystd.h吗?
如果您确实坚持这样做,您可以using通过在嵌套作用域中引入语句来设法做到这一点。例如:
using namespace std;
int main() {
using namespace mystd;
int a[3];
sort(begin(a), end(a));//std::sort
cin_wrapper w;//mystd::cin
}
Run Code Online (Sandbox Code Playgroud)
不过,应该避免任何涉及的事情using namespace std;(使用其他更受限制的命名空间并不是那么糟糕,但那是你打开的一大卡车蠕虫罐头)。