When would lambda functions be useful for classes in C++? -


so, see usefulness of lambda functions when used replace functors, when want use them in object oriented programming (with classes) setting in general , why?

okay, little more (and less) helpful response comment.

closures (that is, functions declared inside other functions, capture outer function's variables) interesting back-channel way implement classes. watch:

auto makecounter(int initialcount) {     int currentcount = initialcount;     struct {         std::function<void()> increment = [&]() { currentcount++; };         std::function<int()> getcount = [&]() { return currentcount; };     } thecounter;      return thecounter; } 

now thecounter structure 2 members, 1 increments count , other retrieves current count. notice struct doesn't need store current count; instead implicitly held 2 lambdas, share currentcount between them.

there's few problems this.

  1. it doesn't compile. not mostly. there ton of things wrong code snippet. actually, it crashes gcc 4.9. whee!
  2. even if did compile, wouldn't work properly, because c++ closures aren't powerful -- can't keep captured variables alive after end of scopes. language actual gc this.
  3. c++ has classes, why bother?

nevertheless, see sort of pattern in other languages either support (proper) closures , gc don't have native facilities classes (e.g. variants of lisp), or support classes crappily it's arguably better things way (e.g. matlab).

so in c++ they're replacing functor boilerplate. don't offer additional power. in other languages, they're rather more versatile, , more important.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -