这可能是一个概念性问题。我正在执行以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
回到原来的问题,什么是合格/于function<void()>
类成员分配lambda
的最佳做法?我看到很多不同的答案,一些使用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 = std :: move(in);'也可以吗? –
@dau_sama这将工作,因为'f'会被分配参数,但它可能不会做调用者的期望。如果你用''std :: function'的非''const'左值引用调用'set_f',它仍然会'移动'参数,这可能不是你想要的。如果你想总是“移动”,你应该改用'F'作为值。 – Praetorian