Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private methods vs Lambda in C++

Tags:

c++

c++11

My question refers to:

Using a lambda expression versus a private method

Now that lambda functors are part of C++, they could be used to unclutter a class' interface. How does lambda use vs private method use compare in C++? Do there exist better alternatives to unclutter class interfaces?

like image 388
user1095108 Avatar asked Sep 14 '13 19:09

user1095108


People also ask

What are the differences between lambda expression function and anonymous function?

A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name. Whereas, Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time.

Is lambda expression An anonymous method?

Lambda expression is an anonymous method that you can use to create delegates or expression tree types.

When should I use private methods?

Private methods are typically used when several methods need to do the exact same work as part of their responsibility (like notifying external observers that the object has changed), or when a method is split in smaller steps for readability.

What is the point of private methods?

Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.


1 Answers

Although lambdas can definitely replace some private member functions, thinking of them as means to uncluttering the interface of a class is taking too narrow a view of both lambdas and private member functions.

Private member functions (and functions in general) are the basic units of code reuse. They let you write a piece of logic once, and then hide it behind the name of the function.

Although lambdas can replace a private member function in certain context, they could replace an object of which that function is a member along with it, which is a whole lot more. Due to lambda's ability to capture the context around them, you get a way of creating code blocks that take not only your object with it, but also the state of your local variables. Before lambdas you needed to create a special class for that; lambdas let you create such classes on the fly, for much better readability.

like image 171
Sergey Kalinichenko Avatar answered Oct 12 '22 09:10

Sergey Kalinichenko