我试图编译这段代码与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());
}
但它似乎不工作:
$ 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> >]
科莫编译此代码,而无需错误。 (4.3.10.1 Beta2,strict C++ 03,no C++ 0x)
这个有效的C++吗?
为什么海湾合作委员会甚至将std::sort
视为一个有效的超载?
我做了一些实验,我想我知道为什么科莫可能编译这个(但我不知道这是事实):
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
}
我的猜测是,第一个电话解析为bar(int*)
,所以没有ADL并且没有歧义,而第二个电话解析为bar(foo::iterator_b)
并且拉入foo::bar
(但我不太确定)。
所以GCC可能使用类似iterator_b
而科莫使用iterator_a
。
我发现科莫行为怪异,这意味着他们的'iterator'不住在'std'命名空间还是我失去了一些东西? – 2010-05-28 08:16:29
我用一些可以玩的代码更新了答案。 – bucels 2010-05-28 08:45:49