gpt4 book ai didi

c++ 17命名空间,是否可以始终强制进行合格访问?

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:27 25 4
gpt4 key购买 nike

令我惊讶的是,当函数在与变量相同的命名空间中声明时,该函数可以不加限定地访问该变量。

// file qqq.cpp

namespace aaa {
void f();
int x;
}

void aaa::f() {
aaa::x; // 0. INTENDED ACCESS to x in namespace aaa (also works)
x; // 1. SURPRISE: x can be accessed without aaa:: qualification
bool x; // 2. SURPRISE: given (1) why is it allowed to redefine x?
}

问题:

A) 有没有什么方法可以确保 namespace 中的所有对象都对其成员视而不见,并且总是需要通过::进行访问?

B) 如果不是,获得所需行为的正确编码实践是什么?

C) 如果不是,另一种解决方案是将每个命名空间分成 2 个,一个用于函数,另一个用于变量,例如 f_aaa 和 v_aaa。但这在实际使用中看起来很笨重和丑陋,例如。 void f_sqlite::myfun() { v_sqlite::myvar; } 而不仅仅是 void sqlite::myfun() { sqlite::myvar;


编辑 1:上下文,我试图解决的“问题”:

重构了几千行代码,命名空间被认为适合捆绑相关元素,例如。用于整个代码库中使用的 sqlite 实用程序函数和变量的“sqlite”命名空间。通过::强制访问将是提高清晰度和避免名称冲突和隐藏的极好方法。为“一个包”单独命名空间将达不到目的。类在概念上似乎不合适。

编辑 2:

D) 当命名空间 aaa 中的函数未经限定访问命名空间 aaa 中的变量时,是否有可能获得警告(启用编译器标志)以发出信号?

编辑 3:

我想我最终还是会使用“单独的命名空间”,但是通过嵌套的命名空间

// file qqq.cpp

namespace aaa::f { // namespace for functions
void f();
void g();
}

namespace aaa::v { // namespace for variables
int x;
}

// definition of function f inside namespace aaa::f

void aaa::f::f() {
aaa::v::x; // only way of accessing x in aaa::v (good) (ugly)
x; // compiler error (good)
bool x; // normal scope hiding (good)
g(); // works: ARGH! would like to force qualifying with aaa::f::
}

不过还是比较丑。和!函数仍然可以不合格地相互调用,对象仍然可以不合格地相互调用/引用。如果能够简单地在命名空间内的所有或某些元素上放置一些“强制限定符”(如“私有(private)”),那真是太好了。

最佳答案

A) is there any way to prevent all objects in a namespace to be blind to its fellow constituents, and to require access always through :: ?

没有。

B) if not, what would be the correct coding practice to obtain the desired behavior?

使用

C) if not, an alternative solution would be to separate the aaa namespace into 2, one for functions and another for variables, like f_aaa and v_aaa. but this seems quite clunky and ugly in practical use, eg. void f_sqlite::myfun() { v_sqlite::myvar; } instead of just void sqlite::myfun() { sqlite::myvar; }

使用将相关函数和数据组合在一起。你想隐藏的内容放在 private 部分。

关于c++ 17命名空间,是否可以始终强制进行合格访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128721/

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