当遍历标准容器时,您认为省略 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;
。这确保它从具有 begin
和 end
成员的其他命名空间中找到容器的 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/