c++ - 如何避免因 Koenig 查找而导致的标准命名冲突

标签 c++ stl namespaces std argument-dependent-lookup

作为学习练习,我一直在reimplementing some of the STL algorithm .即使我没有为 std 命名空间 my test code won't compile unless I explicitly prefix those functions shadowing std names 添加任何 using 指令或 using 声明.

我认为这是由于当我将 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), end(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, I e, 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(...) 的形式进行每次调用.有什么办法可以避免使用完全限定名称来避免与标准名称发生命名冲突?

最佳答案

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), end(v), 3);

关于c++ - 如何避免因 Koenig 查找而导致的标准命名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551930/

相关文章:

c# - 可能与类名和属性名冲突?

c++ - 如何在 for 循环中迭代 `std::stack` 个元素?

ruby-on-rails - 存储在 lib (heroku) 中的生产未初始化常量自定义类

c++ - 为什么我得到 NaN 作为计算结果? (拉格朗日标准形式的分段线性插值)

c++ - 缩写相似的数据成员

c++ - 简要说明引用折叠规则请求 : (1) A& & -> A& , (2) A& && -> A& , (3) A&& & -> A& , 和 (4) A&& && -> A&&

C++ IO 二进制文件流 : default value when output isn't specified

R 安装包加载命名空间

c++ - 如何检查一个字符是否是某个字母表的字母?

c++ - 开发 Windows 窗体应用程序?