Prefer Function Objects to Function Pointers

Prefer Function Objects to Function Pointers

Passing a function pointer is a common practice in event-driven systems, whereby a callback routine is invoked through a pointer. C++, however, offers a better alternative to function pointers: function objects. Using a function object instead of a pointer offers several advantages. First, your code is more resilient to changes, since the object containing the function can be modified without affecting its users. In addition, compilers can inline a function object, thereby enhancing performance even further. But perhaps the most compelling argument in favor of function objects is their genericity. A function object can embody a generic algorithm by means of a member template, something not easily accomplished with ordinary function pointers. In the following example, a function object implements a generic negation operator:

 #include  #include using namespace std;class negate {  public : template < class T > T operator()  (T t) const { return -t;} //generic negation operator };void callback(int n, const negate& neg) { //pass a function object rather than a function pointer  n = neg(n);  // invoke the overloaded () operator to negate n  cout << n;}void main() { callback(5, negate() ); //output -5}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several