我有一个冒泡排序函数,它需要一个数组,一个比较函数和一个布尔值来指示它是否应该颠倒数组。它是一种支持任何数据类型的模板函数,并会自动推导出数组大小。为什么在传递lambda时不能推导出模板参数而不是函数指针
指定比较函数时,如果我传递函数指针,编译器会自动推导出数组的数据类型,这很好。但是如果我传递lambda表达式,它不会自动推断出来。我必须明确指定数据类型,或者将lambda的static_cast
指定为fnCompare_t<double>
。
这是什么原因?因为根据this post,只要lambda没有捕获,它可以像普通旧函数指针一样使用,但似乎并非总是如此?在这种情况下它怎么会有所不同?
#include <iostream>
using namespace std;
template <typename T>
using fnCompare_t = int(*)(T const &, T const &);
template <typename T, size_t count>
inline void BubbleSort(
T(&array)[count],
fnCompare_t<T> fnCompare,
bool reverse)
{
cout << "TODO: Implement BubbleSort" << endl;
}
double doubleArray[] = {
22.3, 11.2, 33.21, 44.2, 91.2, 15.2, 77.1, 8.2
};
int CompareDouble(double const & a, double const & b)
{
return a > b ? 1 : a == b ? 0 : -1;
}
int main()
{
auto fnCompare = [](double const & a, double const & b) -> int {
return a > b ? 1 : a < b ? -1 : 0;
};
// compile OK:
BubbleSort(doubleArray, CompareDouble, false);
BubbleSort(doubleArray, static_cast<fnCompare_t<double>>(fnCompare), false);
BubbleSort<double>(doubleArray, fnCompare, false);
// compile error, could not deduce template argument:
//BubbleSort(doubleArray, fnCompare, false);
return 0;
}
[为什么要使用命名空间std坏习惯](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) –