简体   繁体   English

递归 lambda C++17

[英]Recursive lambda C++17

I have the following situation, I have a class with functions which looks like this:我有以下情况,我有一个 class,其功能如下所示:

void GetTest(int id, std::function<void(Test)> cb);
void GetTest2(long id, std::function(void(Test2)> cb);

The cb method will be called after the method is done which will run in the background, the order of execution of the CB method isn't guaranteed. cb 方法将在方法完成后调用,该方法将在后台运行,CB 方法的执行顺序不保证。

Now I have the case where I need to get a vector of IDs.现在我遇到了需要获取 ID 向量的情况。 So I tried to write a template function to call these methods and call a callback after all IDs were queried.于是我尝试写了一个模板function来调用这些方法,并在查询完所有ID后调用回调。

I came up with the following method:我想出了以下方法:

template <typename T, typename T2>
void QueryList(std::vector<T2> list, std::function<void(std::shared_ptr<std::vector<T>>)> finalCallback) {
    std::shared_ptr<std::vector<T>> ret = std::make_shared<std::vector<T>>();

    auto callback = [this, list, ret, finalCallback](size_t i, auto callback, T res) {
        ret->push_back(res);

        if (i + 1 < list.size()) {
            GetTest(list[i + 1], [callback, i](T test) { callback(i + 1, callback, test); });
        } else {
            finalCallback(ret);
        }
    };

    GetTest(list[0], [callback](T test) { callback(0, callback, test); });
}

But this results in the following error error C3779: 'QueryList::<lambda_6d76c4236d9122e99fd2ab44986c7643>::operator ()': a function that returns 'auto' cannot be used before it is defined但这会导致以下错误error C3779: 'QueryList::<lambda_6d76c4236d9122e99fd2ab44986c7643>::operator ()': a function that returns 'auto' cannot be used before it is defined

You should specify the return type of the lambda:您应该指定 lambda 的返回类型:

template <typename T, typename T2>
void QueryList(std::vector<T2> list, std::function<void(std::shared_ptr<std::vector<T>>)> finalCallback) {
    std::shared_ptr<std::vector<T>> ret = std::make_shared<std::vector<T>>();

    auto callback = [this, list, ret, finalCallback](size_t i, auto callback, T res) -> void {
//                                                                                   ^^^^^^^
        ret->push_back(res);

        if (i + 1 < list.size()) {
            GetTest(list[i + 1], [callback, i](T test) { callback(i + 1, callback, test); });
        } else {
            finalCallback(ret);
        }
    };

    GetTest(list[0], [callback](T test) { callback(0, callback, test); });
}

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

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