加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 基于范围的For循环和ADL

发布时间:2020-12-16 03:40:00 所属栏目:百科 来源:网络整理
导读:这是2011年这个问题的延伸: Range-based for loops and ADL 使用Visual Studio 2015,我无法使用Argument Dependent Lookup(ADL)为自定义容器创建基于范围的for循环. 我在下面用一个自定义容器做了一个非常简单的测试用例: #include vectornamespace Foo{ t
这是2011年这个问题的延伸:
Range-based for loops and ADL

使用Visual Studio 2015,我无法使用Argument Dependent Lookup(ADL)为自定义容器创建基于范围的for循环.

我在下面用一个自定义容器做了一个非常简单的测试用例:

#include <vector>

namespace Foo
{
    template <typename T>
    class Container
    {
    public:

        std::vector<T> values;
    };
}

template <typename T>
typename std::vector<T>::iterator begin(Foo::Container<T>& foo)
{
    return foo.values.begin();
}

template <typename T>
typename std::vector<T>::iterator end(Foo::Container<T>& foo)
{
    return foo.values.end();
}

使用此容器和ADL,以下测试编译完全正常:

int main(int argc,char* argv[])
{
    Foo::Container<int> values;

    for (auto it = begin(values); it != end(values); ++it)
    {
        ...
    }

    return 0;
}

正如它应该.我不确定ADL是否在这里使用,但无论如何,这都是有道理的.从MSDN documentation开始,我们有:

Keep in mind these facts about range-based for:

  • Automatically recognizes arrays.

  • Recognizes containers that have .begin() and .end().

  • Uses argument-dependent lookup begin() and end() for anything else.

根据我对ADL的理解以及上面的文档,还应该编译以下内容:

int main(int argc,char* argv[])
{
    Foo::Container<int> values;

    for (auto value : values)
    {
        ...
    }

    return 0;
}

但事实并非如此.相反,我得到以下错误:

error C3312: no callable 'begin' function found for type 'Foo::Container<int>'
error C3312: no callable 'end' function found for type 'Foo::Container<int>'

那么这里发生了什么?我对ADL的解释是否不正确,或者这是MSVC 14.0编译器的错误?

解决方法

您必须将begin和end放在Foo名称空间中才能使ADL正常工作.这是因为ADL将查找相应参数的名称空间以搜索begin和end的定义.
namespace Foo
{
    template <typename T>
    class Container
    {
    public:

        std::vector<T> values;
    };

    template <typename T>
    typename std::vector<T>::iterator begin(Foo::Container<T>& foo)
    {
        return foo.values.begin();
    }

    template <typename T>
    typename std::vector<T>::iterator end(Foo::Container<T>& foo)
    {
        return foo.values.end();
    }
}

UPD:不考虑全局命名空间的开始和结束的原因是因为更新的标准说在关联的命名空间中查找了开始和结束,但是没有执行普通的不合格的查找.这是标准中错误修复的结果(http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1442).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读