c ++ - 函数模板调用中的<unresolved overloaded =“”function =“”type =“”>

时间:2016-11-20 12:32:03

标签: c++ c++11 templates c++14 function-pointers

我有一个select [priority], count(distinct job_id) as total_priority, count(distinct job_id) * 100.0 / sum(count(distinct job_id)) over () as ratio from task_events t group by [priority]; ,有两个属性val(float)和i(int)。我创建了class A函数实现quicksort,它接受两个函数指针 - 第一个接受两个A类对象,它允许我选择要排序的属性,第二个是模板函数,它允许我选择是否排序增加或减少顺序。实施如下:

sort()

但是,当从#include <iostream> #include <vector> class A{ float val; int i; public: A(float v, int j): val(v), i(j){} //constructor float getVal(){ return val;} float getI(){ return i;} }; template <typename T> bool compareVal(A _One, A _Two, bool (*comparator)(T,T)){ return comparator(_One.getVal(),_Two.getVal());} template <typename T> bool compareI(A _One, A _Two, bool (*comparator)(T,T)){ return comparator(_One.getI(),_Two.getI());} template <typename T> bool less(T a, T b){ return a<b; } template <typename T> bool greater(T a, T b){ return a>b; } //a quicksort program template <typename T> void sort(std::vector<A>& _as, int left, int right, bool (*compare)(A, A), bool (*comparator)(T,T)){ int i = left, j = right; int middle = (left + right)/2;; if (right - left < 1) return; while (i <= j) { while (compare(_as[i],_as[middle], comparator)) i++; //compare called while (compare(_as[middle],_as[j], comparator)) j--; //compare called if (i <= j) { std::swap(_as[i], _as[j]); i++; j--; } } if (left < j) sort(_as, left, j, compare, comparator); if (i < right) sort(_as, i, right, compare, comparator); } int main(){ std::vector<A> v; //some inserts sort(v, 0, v.size()-1, compareVal, less<float>); // first call sort<float>(v, 0, v.size()-1, compareVal, less); // second call sort<float>(v, 0, v.size()-1, compareVal, less<float>); //third call return 0; } 调用sort()函数时,它会在所有三个实例中产生编译器错误:

main()

我无法理解错误。看一下之前与之相关的一些stackoverflow问题,但仍然没有。如何使这个程序工作?

1 个答案:

答案 0 :(得分:2)

compare被声明为bool(*)(A, A),但compareValcompareI都具有bool(*)(A, A, bool(*)(T, T))类型。相应地更改sort的签名:

template <typename T>
void sort(std::vector<A>& _as, int left, int right,
              bool (*compare)(A, A, bool(*)(T, T)),
              bool (*comparator)(T, T)){
    ...
}

或者,完全抛弃函数指针并使用模板来允许使用任何可调用的函数(例如lambdas):

template <typename T, typename CompareT, typename ComparatorT>
void sort(std::vector<A>& _as, int left, int right,
              CompareT compare, ComparatorT comparator {
    ...
}