问题描述
我在C ++中练习lambda函数,以下代码可以正常工作
void insertionSort(int* a,int size,bool reverse=false) {
auto comp = [](int a,int b,bool reverse) {
return reverse ? a > b : b < a;
};
for (int i = 0; i < size; i++) {
int current = a[i];
cout << current <<endl;
int j = i-1;
while (j >= 0 && comp(current,a[j],reverse)) {
a[j+1] = a[j]; //shift right
j--;
}
a[j+1] = current;
}
show(a,size); //another function which prints all elements of a
}
但是如果我改变
auto comp = [](int a,bool reverse) {
使用
bool comp = [](int a,bool reverse) {
GCC编译器在编译时引发以下错误
error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current,reverse)) {
那么这是预期的吗?什么是一般规则?我是否总是将返回类型指定为auto
?
解决方法
在第一个代码段中,comp
的类型是lambda的类型,它是唯一的未命名类类型,(这就是我们使用auto
的原因,明确指定类型)。请注意,它不是lambda的返回类型(即bool
)。
如果您要明确指定lambda的返回类型,则可以
auto comp = [](int a,int b,bool reverse) -> bool {
// ^^^^^^^
顺便说一句:不捕获的lambda可以转换为函数指针,然后隐式转换为bool
。因此,如果将comp
的类型更改为bool
,则其值始终为true
。如错误消息所述,您不能将其用作函子。
编写auto comp = [](int a,bool reverse) {
时,comp具有唯一的lambda类型,C ++编译器会创建一个结构名称comp。但是当您编写bool comp = [](int a,bool reverse) {
时,comp的类型为bool,并且只能采用bool值。