在 C++14 中使用通用 lambda 函数进行递归
Recursion with generic lambda functions in C++14
我遇到了 this question, where the answer describes nice detail about how can the generic lambda functions be used to replace the std::function
technique 以及如何重新连接停止条件以启用 return 类型推导。
基于以上内容,我创建了以下工作示例:
#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&&
是无害的,意思是"I do not mind if this is a temprary or whatever, just don't make a copy",在这里表达的意思很好。 auto&
声明 "No temporaries allowed!" 有时你想在引用时排除临时对象,但这种情况很少见。
auto const&
、auto
和 auto&&
应该是您的生计。
仅当您的操作明确涉及编写 和 时才使用 auto&
您可以排除代理引用。
我遇到了 this question, where the answer describes nice detail about how can the generic lambda functions be used to replace the std::function
technique 以及如何重新连接停止条件以启用 return 类型推导。
基于以上内容,我创建了以下工作示例:
#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&&
是无害的,意思是"I do not mind if this is a temprary or whatever, just don't make a copy",在这里表达的意思很好。 auto&
声明 "No temporaries allowed!" 有时你想在引用时排除临时对象,但这种情况很少见。
auto const&
、auto
和 auto&&
应该是您的生计。
仅当您的操作明确涉及编写 和 时才使用 auto&
您可以排除代理引用。