模板函数重载错误C2688

overloading of template function error C2688

本文关键字:错误 C2688 重载 函数      更新时间:2023-10-16

我无法编译以下代码

namespace sequential_sort
{
template<class T>
void sort(std::list<T>& source)
{
    sort(source.begin(), source.end()); //(1)
}
template<class Iter>
void sort(Iter begin, Iter end)
{
    if(begin == end)
         return;
    typedef Iter::value_type value_type;
    value_type value = *(begin);
    Iter part = std::partition(begin, end, [&value](const    value_type&->bool{return   t < value;});
    sort(begin, part);
    Iter divide = part;
    divide++;
    sort(divide, end); 
}
}

它说,在第(1)行,我有错误C2688,对重载函数的调用不明确。我不明白为什么重载的函数甚至有不同数量的参数?

有几个问题在起作用:

1) 您需要在双参数函数之前声明您的单参数sequential_sort::sort函数,除非您想要另一个sort函数。你可能看不到它的效果,因为你使用的是Windows C++编译器,它在这方面不符合标准。应该发生的是,std::sort是明确选择的,这不会编译,因为它需要随机访问迭代器(std::list有一个sort成员函数,应该使用它来代替std::sort)。

2) 一旦修复,由于要将std::list迭代器传递给两个参数的sort依赖于参数的查找(ADL)意味着也要考虑std::sort。这就是造成歧义的原因。您可以通过具体说明要使用哪两个参数sort来解决此问题:

#include <list>
#include <algorithm>
namespace sequential_sort
{
template<class Iter>
void sort(Iter begin, Iter end) { }
template<class T>
void sort(std::list<T>& source)
{
  sequential_sort::sort(source.begin(), source.end()); //(1)
//^^^^^^^^^^^^^^^
}
}