简体   繁体   中英

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

This is code inside my mergeSort method,

    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).

But instead the compiler complains saying:

Variable 'mergeSortRange' declared with 'auto' cannot appear in its own initializer.

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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