简体   繁体   English

如果返回类型从 auto 更改为 bool,则 Lambda function 抛出错误

[英]Lambda function throwing error if return type is changed from auto to bool

I was practicing lambda functions in C++, following code works fine我在 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
}

but if I change但如果我改变

    auto comp = [](int a, int b, bool reverse) {

with

    bool comp = [](int a, int b, bool reverse) {

GCC compiler throws following error while compiling error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) { GCC 编译器在编译错误时抛出以下错误error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) { error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) {

So is this expected?这是预期的吗? What is general rule?什么是一般规则? Shall I always specify return type as auto ?我应该始终将返回类型指定为auto吗?

In the 1st code snippet, comp 's type is the type of the lambda , it's a unique unnamed class type, (that's why we use auto , we can't specify the type explicitly).在第一个代码片段中, comp的类型是lambda的类型,它是唯一的未命名 class 类型,(这就是我们使用auto的原因,我们不能明确指定类型)。 Note that it's not the return type of the lambda (ie bool ).请注意,它不是 lambda 的返回类型(即bool )。

If you want to specify the return type of the lambda explicitly you can如果要明确指定 lambda 的返回类型,可以

auto comp = [](int a, int b, bool reverse) -> bool {
//                                         ^^^^^^^

BTW: Non-capturing lambdas could convert to function pointer and then convert to bool implicitly.顺便说一句:非捕获 lambda 可以转换为 function 指针,然后隐式转换为bool So if you change the type of comp to bool its value is always true .因此,如果您将comp的类型更改为bool ,其值始终为true As the error message said, you just can't use it as functor.正如错误消息所说,您不能将其用作仿函数。

When you write auto comp = [](int a, int b, bool reverse) { , comp has the unique type lambda aka, C++ compiler creates a struct names comp.当您编写auto comp = [](int a, int b, bool reverse) {时,comp 具有唯一类型 lambda aka C++ 编译器会创建一个结构名称 comp。 But when you write bool comp = [](int a, int b, bool reverse) { , comp has the type bool and can only take bool values.但是当您编写bool comp = [](int a, int b, bool reverse) {时, comp 具有 bool 类型并且只能采用 bool 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM