简体   繁体   English

在C ++ 14中使用通用Lambda函数进行递归

[英]Recursion with generic lambda functions in C++14

I came across this question, where the answer describes nice detail about how can the generic lambda functions be used to replace the std::function technique and how to rewire the stop condition to enable the return type deduction. 我碰到了这个问题, 答案在其中详细描述了如何使用通用Lambda函数代替std::function技术以及如何重新连接停止条件以启用返回类型推导。

Based on the above I created the following working example: 基于上述内容,我创建了以下工作示例:

#include <cstdio>

void printSeq(unsigned start) {
    auto recursion = [](auto&& self, const char* format, unsigned current) {
        printf(format, current);
        if(!current)
            return static_cast<void>(printf("\n"));
        else
            self(self, ", %u", current - 1);
    };

    recursion(recursion, "%u", start);
}

int main() {
    return (printSeq(15), 0);
}

My question is that what's the advantage using auto&& over the auto& in this case? 我的问题是,在这种情况下,使用auto&&相对于auto&有什么优势? Should I use the std::move here? 我应该在这里使用std::move吗?

auto& is lvalue only. auto&仅是左值。

This matters little until you refactor and replace the lvalue recursive object with a temporary proxy memoizer, for example. 直到您重构并用临时代理备注器替换左值递归对象为止,这无关紧要。

auto&& is harmless, and means "I do not mind if this is a temprary or whatever, just don't make a copy", which expresses meaning well here. auto&&是无害的,意思是“我不介意这是临时的还是其他东西,只是不要复制”,在这里很好地表达了意思。 auto& states "No temporaries allowed!" auto&指出“不允许临时使用!” Sometimes you want to exclude temporaries when making a reference, but it is rare. 有时您在引用时要排除临时对象,但这很少见。

auto const& , auto and auto&& should be your bread and butter. auto const&autoauto&&应该是您的面包和黄油。

Only use auto& if your operation is explicitly about writing and you are ok with excluding proxy references. 仅当您的操作明确涉及编写并且可以排除代理引用时,才使用auto&

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

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