Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Functional -- Why?

In C++ Standard Template Library, there's a 'functional' part, in which many classes have overloaded their () operator.

Does it bring any convenience to use functions as objects in C++?

Why can't we just use function pointer instead? Any examples?

like image 366
Determinant Avatar asked Mar 09 '12 02:03

Determinant


2 Answers

Ofcourse, One can always use Function pointers instead of Function Objects, However there are certain advantages which function objects provide over function pointers, namely:

  • Better Performance:

One of the most distinct and important advantage is they are more likely to yield better performance. In case of function objects more details are available at compile time so that the compiler can accurately determine and hence inline the function to be called unlike in case of function pointers where the derefencing of the pointer makes it difficult for the compiler to determine the actual function that will be called.

  • Function objects are Smart functions:

Function objects may have other member functions and attributes.This means that function objects have a state. In fact, the same function, represented by a function object, may have different states at the same time. This is not possible for ordinary functions. Another advantage of function objects is that you can initialize them at runtime before you use/call them.

  • Power of Generic programming:

Ordinary functions can have different types only when their signatures differ. However, function objects can have different types even when their signatures are the same. In fact, each functional behavior defined by a function object has its own type. This is a significant improvement for generic programming using templates because one can pass functional behavior as a template parameter.

like image 117
Alok Save Avatar answered Oct 03 '22 23:10

Alok Save


Why can't we just use function pointer instead? Any examples?

Using C style function pointer cannot leverage the advantage of inlining. Function pointer typically requires an additional indirection for lookup.
However, if operator () is overloaded then it's very easy for compiler to inline the code and save an extra call, so increase in performance.

The other advantage of overloaded operator () is that, one can design a function which implicitly considers the function object as argument; no need to pass it as a separate function. Lesser the hand coded program, lesser the bugs and better readability.

This question from Bjarne Stroustrup (C++ inventor) webpage explains that aspect nicely.

C++ Standard (Template) Library uses functional programming with overloaded operator (), if it's needed.

like image 22
iammilind Avatar answered Oct 03 '22 23:10

iammilind