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

c – 如何避免由于Koenig查找引起的std命名冲突

发布时间:2020-12-16 10:08:05 所属栏目:百科 来源:网络整理
导读:作为一个学习练习,我已经 reimplementing some of the STL algorithm了.即使我没有添加任何using指令或使用std命名空间 my test code won’t compile unless I explicitly prefix those functions shadowing std names的声明. 我假设这是由于参数依赖查找在
作为一个学习练习,我已经 reimplementing some of the STL algorithm了.即使我没有添加任何using指令或使用std命名空间 my test code won’t compile unless I explicitly prefix those functions shadowing std names的声明.

我假设这是由于参数依赖查找在我将std :: vector迭代器作为参数传递给我的函数时从std命名空间引入函数.

一个小程序来说明我的问题:

#include <vector>
#include <algorithm>

namespace danstd {
template <typename I,typename T>
I find(I b,I e,T val) {
    for (; b != e; ++b) {
        if (*b == val)
            return b;
    }
    return e;
}   
}

using namespace danstd;

int main() {
    std::vector<int> v = {1,2,3};

    auto i = find(begin(v),end(v),3);
    return i == end(v) ? -1 : *i;
}

编译时,我看到以下错误消息:

$g++ -Wall foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:16:37: error: call of overloaded ‘find(std::vector<int>::iterator,std::vector<int>::iterator,int)’ is ambiguous
     return *find(begin(v),3);
                                     ^
foo.cpp:5:3: note: candidate: I find(I,I,T) [with I = __gnu_cxx::__normal_iterator<int*,std::vector<int> >; T = int]
 I find(I b,T val) {
   ^~~~
In file included from /usr/include/c++/6/algorithm:62:0,from foo.cpp:2:
/usr/include/c++/6/bits/stl_algo.h:3784:5: note: candidate: _IIter std::find(_IIter,_IIter,const _Tp&)[with _IIter = __gnu_cxx::__normal_iterator<int*,std::vector<int> >; _Tp = int]
     find(_InputIterator __first,_InputIterator __last,^~~~

在单元测试代码中,我已经链接到上面,我已经将我的函数包装在danstd命名空间中,并且我在表单danstd :: function(…)上进行了每次调用.是否有任何方法可以使用完全限定名称来避免与std名称的命名冲突?

解决方法

I assume that this is due to argument dependent lookup bringing in functions from the std namespace when I pass std::vector iterators as parameters to my functions.

那是正确的.由于std :: vector :: iterator存在于std中,它将在std中进行查找.

Is there any way around having to use fully qualified names to avoid the naming conflicts with std names?

很不幸的是,不行.你需要有资格从全球范围内想要一个像

return *::find(begin(v),3);

(编辑:李大同)

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

    推荐文章
      热点阅读