开始使用C++11特性,碰到一些问题。以下写了一个快速排序的函数模板,划分操作的比较函数使用一个std::function<int(T,T)>的参数接收,而在main中使用函数模板接收一个lambda函数[](int a, int b) -> int {return a < b;}时报错,函数不匹配。这里该如何处理?
#include <iostream>
#include <functional>
template <typename T>
void Swap(T *a, T *b) {
T tmp = *a;
*a = *b;
*b = tmp;
}
template <typename T>
int partition(T array[], int low, int high, const std::function<int(T, T)> &cmp) {
int i = low - 1;
T x = array[high];
for (int j = low; j < high; j++) {
if (cmp(array[j], x)) {
i++;
Swap(&array[j], &array[i]);
}
}
Swap(&array[i + 1], &array[high]);
return i + 1;
}
template <typename T>
void quicksort(T array[], int low, int high, const std::function<int(T, T)> &cmp) {
if (low < high) {
int mid = partition(array, low, high, cmp);
quicksort(array, low, mid - 1, cmp);
quicksort(array, mid + 1, high, cmp);
}
}
int main() {
std::cout << "Hello, World!" << std::endl;
int arr[] {5, 3, 9, 1, 6, 2};
quicksort(arr, 0, 5, [](int a, int b) -> int {
return a < b;
});
for(auto item: arr) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
报错信息:
E:\Project\DesignPattern\main.cpp: In function 'int main()':
E:\Project\DesignPattern\main.cpp:39:6: error: no matching function for call to 'quicksort(int [6], int, int, main()::<lambda(int, int)>)'
});
^
E:\Project\DesignPattern\main.cpp:26:6: note: candidate: template<class T> void quicksort(T*, int, int, const std::function<int(T, T)>&)
void quicksort(T array[], int low, int high, const std::function<int(T, T)> &cmp) {
^
E:\Project\DesignPattern\main.cpp:26:6: note: template argument deduction/substitution failed:
E:\Project\DesignPattern\main.cpp:39:6: note: 'main()::<lambda(int, int)>' is not derived from 'const std::function<int(T, T)>'
});
^
迷茫2017-04-17 15:23:10
The type of T cannot be deduced before
lambda is converted to const std::function<int(T, T)>&
.
You can add an auxiliary class to determine the type of std::function
first, and then perform implicit conversion of lambda.
tempalte<typename T>
struct type_deduce
{
using type = T;
};
template<typename T>
void quicksort(T array[], int low, int high, const typename type_deduce<std::function<int(T, T)>>::type& cmp)
高洛峰2017-04-17 15:23:10
User-defined type conversion will not be performed during type derivation, that is, conversion from lambda expression to std::function will not be performed. So kneel down here.
What you need here is a BinaryPredicate. Just write Fn &&fn directly. Then perform a BinaryPredicate check on Fn.
Or turn T into a non deduction context, such as
template <typename T>
void quicksort(T array[], int low, int high,
const std::function<int (
decltype(std::declval<T>()),
decltype(std::declval<T>()))> &cmp)
or
template <class T>
struct BinaryPredicateType {
using type = std::function<int (T, T)>;
};
template <typename T>
void quicksort(T array[], int low, int high,
const typename BinaryPredicateType<T>::type &cmp)