这可能是一个概念性问题。我正在实现接受 lambda
作为参数的函数。然而,我无法理解 lambda
的确切类型。例如:
auto T = [] () { printf("hello world\n"); };
auto F = move(T);
T(); // print "hello world"
F(); // print "hello world"
我以为在调用T
的move
方法之后,T
的内容会消失。换句话说,我期望有如下行为:
function<void> T = [] () { printf("hello world\n");};
auto F = move(F);
F(); // print "hello world"
T(); // throw error
回到最初的问题,如何最佳实践地传递/赋值一个
lambda
给function<void()>
类成员?我看到了许多不同的答案,一些使用const function<void()>&
,另外一些则建议使用模板F&&
。struct Foo {
function<void()> f;
// Option 1:
void set_f(const function<void()>& in) {f=in;}
// Option 2: template
template <typename F>
void set_f(F&& in) { // what to write here??? }
}
这两个选项是否足够通用以涵盖大多数输入类型?
f
被分配参数而言,它可以工作,但它可能不会做调用者期望的事情。如果您使用非“const”左值引用调用set_f
到std::function
,它仍将“move”参数,这可能不是您想要的。如果您想始终“move”,则应该通过值获取F
。 - Praetorian