gpt4 book ai didi

c++ - 是否可以通过 using namespace 重用变量名?

转载 作者:可可西里 更新时间:2023-11-01 18:39:28 25 4
gpt4 key购买 nike

比如最初我有一个示例程序:

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int a[3];
sort(begin(a),end(a));
cin;
}

现在我想修改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;
}

但是改起来好像不太方便。(用户必须提到所有组件 using std::sort;using mystd::cin; 或将所有 cin 替换为 mystd::cinusing 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;
}

我尝试在 mystd 中添加 using namespace std; 但它也会导致歧义。

我能想到的一个复杂的解决方案是在 mystd 中为所有未修改的 std 成员创建一个类似 using std::string; 的 using 语句。

有没有更实用的方法来实现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
}

任何涉及 using namespace std; 的事情都应该避免(使用其他更受限制的 namespace 并不是那么糟糕,但那是你打开的一大堆蠕虫)。

关于c++ - 是否可以通过 using namespace 重用变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com