“使用”的候选标准函数

发布于 2024-10-29 03:53:41 字数 492 浏览 2 评论 0原文

我知道使用 std::swap 通过 ADL 启用用户定义的 swap 函数的技术,但我不知道这也应该应用于其他一些功能。例如,我在模板代码中滥用 std::abs ,而我应该使用类似的内容:

template <class Int> void f(Int i) {
    using std::abs;
    Int j = abs(i);
    // ...
}

您能想到应该以这种方式使用什么标准函数?

附带说明:当包含 cstdlib 时,g++ 将 abs 放入全局命名空间(实际上 ctsdlib 包含 stdlib.h > (定义函数 abs)并执行#undef abs...),标准是怎么说的?

I knew the technique of using std::swap to enable via ADL the use of user defined swap functions, but I was not aware that this should be applied also to some other functions. For example I was writing abusively std::abs in template code wheras I should have used something like:

template <class Int> void f(Int i) {
    using std::abs;
    Int j = abs(i);
    // ...
}

What standard function can you think of which should be used this way?

On a side note: g++ puts abs in the global namespace when including cstdlib (in fact ctsdlib includes stdlib.h (which defines the function abs) and does a #undef abs...), what does the standard says?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心清如水 2024-11-05 03:53:41

这是来自标准:

3.4.6 using 指令和命名空间别名
[基本.lookup.udir]
在 using 指令中查找名称空间名称或
命名空间别名定义,仅命名空间
考虑名称。

因此,您可以使用关键字 using 将变量、类型和函数导入到当前命名空间中。


编辑

您可以将任何您喜欢的内容导入到当前命名空间中,但您应该注意命名空间污染,因此尽量不要在标头中使用 using ,而只能在源文件中使用。

理想情况下,您不应使用此关键字。当我有深度嵌套的命名空间时,我有时会使用它。

This is from the standard :

3.4.6 Using-directives and namespace aliases
[basic.lookup.udir]
When looking up a namespace-name in a using-directive or
namespace-alias-definition, only namespace
names are considered.

Therefore, you can use the keyword using to import variable, types and functions into the current namespace.


EDIT

You can import anything you like into the current namespace, but you should care for namespace polution, therefore try not to use using in headers, but only in the source files.

Ideally, you shouldn't be using this keyword. I use it sometimes when I have deeply nested namespaces.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文