依靠ADL的std :: begin()和std :: end()? [英] Relying on ADL for std::begin() and std::end()?
本文介绍了依靠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屋!
查看全文