C++中的奇怪重载规则

buc*_*els 4 c++ templates overloading namespaces g++

我正在尝试使用GCC 4.5.0编译此代码:

#include <algorithm>
#include <vector>

template <typename T> void sort(T, T) {}

int main()
{
    std::vector<int> v;
    sort(v.begin(), v.end());
}
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用:

$ g++ -c nm.cpp
nm.cpp: In function ‘int main()’:
nm.cpp:9:28: error: call of overloaded ‘sort(std::vector<int>::iterator, std::vector<int>::iterator)’ is ambiguous
nm.cpp:4:28: note: candidates are: void sort(T, T) [with T = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
/usr/lib/gcc/i686-pc-linux-gnu/4.5.0/../../../../include/c++/4.5.0/bits/stl_algo.h:5199:69: note:                 void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
Run Code Online (Sandbox Code Playgroud)

Comeau编译这段代码没有错误.(4.3.10.1 Beta2,严格的C++ 03,没有C++ 0x)

这是有效的C++吗?

为什么GCC甚至考虑std::sort作为有效的过载?


我做了一些实验,我想我知道为什么Comeau 可以编译这个(但我不知道这个事实):

namespace foo {
typedef int* iterator_a;
class        iterator_b {};
template <typename T> void bar(T) {}
}

template <typename T> void bar(T) {}

int main()
{
    bar(foo::iterator_a()); // this compiles
    bar(foo::iterator_b()); // this doesn't
}
Run Code Online (Sandbox Code Playgroud)

我的猜测是第一个调用解析为bar(int*)没有ADL且没有歧义,而第二个调用解析bar(foo::iterator_b)并拉入foo::bar(但我不确定).

所以GCC可能会使用iterator_bComeau使用的东西iterator_a.

Joe*_*oeG 8

您可以sort通过完全限定名称来明确指定您的功能::sort.

模糊的重载是由于参数依赖的查找.C++标准没有规定std::vector<*>::iterator应该如何实现.gcc库编写者选择使用__gnu_cxx::__normal_iterator带有模板类型参数的template()std::vector,这会将命名空间std带入相关命名空间的列表中.


这是有效的C++吗?

是的,但两个编译器的行为也符合C++标准.从这个角度来看,ADL引起了巨大的麻烦,直到标准化之后才能理解其全部后果.