简体   繁体   English

为什么不能在递归lambda函数中使用auto?

[英]Why can I not use auto in a recursive lambda function?

This is code inside my mergeSort method, 这是我的mergeSort方法中的代码,

    std::function<void(std::vector<T>*)> mergeSortRange = [&](std::vector<T>* array) -> void {
        int length = (int) array->size();
        if (length < 2)
            return;
        std::vector<T>* leftArr = new std::vector<T>(array->begin(), array->begin() + length / 2);
        std::vector<T>* rightArr = new std::vector<T>(array->begin() + length / 2, array->end());
        mergeSortRange(leftArr);
        mergeSortRange(rightArr);
        mergeTwoSortedArrrays(leftArr, rightArr, array);
        delete leftArr;
        delete rightArr;
    };

I could have substituted the first line with: 我可以将第一行替换为:

auto mergeSortRange = [&](std::vector<T>* array) -> void , and I'd expect it to work fine (excuse my ignorance). auto mergeSortRange = [&](std::vector<T>* array) -> void ,我希望它能正常工作(对不起,请原谅)。

But instead the compiler complains saying: 但是相反,编译器抱怨说:

Variable 'mergeSortRange' declared with 'auto' cannot appear in its own initializer. 用'auto'声明的变量'mergeSortRange'不能出现在它自己的初始化器中。

I have specified both the parameters and the return type. 我已经指定了参数和返回类型。 Could somebody throw some light on this? 有人可以对此有所启发吗?

Your program is ill-formed because as Riad says, you are trying to call the function before the type is deduced: 您的程序格式错误,因为正如Riad所说,您试图在推导类型之前调用该函数:

dcl.spec.auto/10 If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. dcl.spec.auto/10如果需要使用具有未推导占位符类型的实体的类型来确定表达式的类型,则程序格式错误。 Once a non-discarded return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements. 但是,一旦在函数中看到未丢弃的return语句,则从该语句推断出的返回类型就可以在该函数的其余部分中使用,包括在其他return语句中。

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

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