c++ - std::begin() 和 std::end() 依赖 ADL?

标签 c++

当遍历标准容器时,您认为省略 std:: 前缀并依靠 ADL 来查找定义是个好主意吗?示例:

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;。这确保它从具有 beginend 成员的其他命名空间中找到容器的 std 函数,但在它们的命名空间中没有自由函数。

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

关于c++ - std::begin() 和 std::end() 依赖 ADL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242542/

相关文章:

c++ - 无法在 C++ Actor Framework 中声明模板类型的 actor

c++ - gcc 的 std::bind 在哪里将参数复制到数据结构中?

c++ - 将对象推送到 vector 时无输出

c++ - 如何在 docker 中使用静态 opencv 库编译 C++ 应用程序

c++ - 通过本地网络中的OpenCV(C++)实时流式传输图像

C++ D3DX 字体和转换(需要 d3d9 和 d3d10 解决方案)

c++ - 使用迭代器和可变参数模板的笛卡尔积

c++ - sqlite3_step() 似乎不起作用

c++ - 有类似 "default comparator"的东西吗?

c++ - C++ 中的无限 While 循环