我遇到了this问题,answer在哪里详细描述了如何使用通用 lambda 函数来替换 std::function
technique以及如何重新连接停止条件以启用返回类型推导。
基于上述内容,我创建了以下工作示例:
#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);
}
我的问题是,在这种情况下使用 auto&&
相对于 auto&
有什么优势?我应该在这里使用 std::move
吗?
最佳答案
auto&
仅是左值。
这并不重要,除非您重构并用临时代理内存器替换左值递归对象。
auto&&
是无害的,意味着“我不介意这是临时的还是其他什么,只是不要复制”,这在这里很好地表达了含义。 auto&
表示“不允许临时!”有时您想在引用时排除临时变量,但这种情况很少见。
auto const&
、auto
和 auto&&
应该是您的面包和黄油。
如果您的操作明确涉及写入,并且您可以排除代理引用,则仅使用 auto&
。
关于c++ - C++14 中通用 lambda 函数的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45000569/