lundi 25 avril 2016

apply move on a lambda closure

This might be a conceptual question. I am implementing functions taking lambda as parameters. However, I couldn't understand the exact type of a lambda. For example:

auto T = [] () { printf("hello world\n"); };
auto F = move(T);
T();  // print "hello world"
F();  // print "hello world"

I thought after calling move on T, the content of T disappeared. In other words, I expect the following behavior:

function<void> T = [] () { printf("hello world\n");};
auto F = move(F);
F();  // print "hello world"
T();  // throw error

Back to the original question, what is the best practice of passing/assigning a lambda to a class member of function<void()>? I saw many different answers, some using const function<void()>& and others suggesting template 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??? }  
}

Are these two options general enough to capture most input types?

Aucun commentaire:

Enregistrer un commentaire