依靠ADL的std :: begin()和std :: end()? [英] Relying on ADL for std::begin() and std::end()?

查看:156
本文介绍了依靠ADL的std :: begin()和std :: end()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当迭代标准容器时,你认为省略 std :: 前缀并依靠ADL找到定义是个好主意吗?示例:

When iterating over a standard container, do you think it's a good idea to omit the std:: prefix and rely on ADL to find the definition? Example:

std::vector<int> vec = get_vec();
// range-based for loop would be preferred here, but just for the sake of example
for (auto it = begin(vec), end = end(vec); it != end; ++it) { /*...*/ }

有什么理由做这个?

推荐答案

如果要使用ADL能够更改容器类型而不更改循环, using std :: begin;使用std :: end; 。这确保它从具有 begin end的其他命名空间找到 std 成员,但在其命名空间中没有自由函数。

If you're going to use ADL to be able to change the container type without changing the loops, then add using std::begin; using std::end;. That makes sure it finds the std functions for containers from other namespaces that have begin and end members, but no free functions in their namespace.

namespace my {
    template <typename T>
    struct container {
        // ... stuff
        iterator begin();
        iterator end();
    };
    // no begin/end free functions
}


my::container<int> vec = get_vec();
using std::begin;
using std::end;
for (auto it = begin(vec), end = end(vec); it != end; ++it) { /*...*/ }
// defaults to std::begin which defaults to .begin() member function

这篇关于依靠ADL的std :: begin()和std :: end()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆