In: Computer Science
In C++ please.
7. Define a callback. Name three kinds of callbacks that we
studied. Simplify the following code using a lambda-expression.
bool notZero(int e){return e!=0;}
...
auto it=find_if(vect.begin(), vect.end(), notZero);
Callback in C++
Callback or call-after function is any executable code that is passed as an argument to another
code,that other code is expected to execute(callback) the argument at a given time.
Example:
#include<iostream>
void A1() { //void is a return type like int
cout << "A1 function"; //print A1 function
}
void A2() {
cout <<"A2 function";
}
int main() {
void(*p) (); //function pointer
p= A1;
p() //output: A1 function
p=A2;
p(); //output: A2 function
}
3 kinds of Callback:
1) Function Pointer - See above example.
2) Function Objects/Functors
A functor is an object that acts like a function.
To create a functor ,we create a object that overloads the operator ().
Example code of Functor:
#include<iostream>
using namespace std;
class A1 {
int num; //variable declared
public:
A1() //constructor
{
num=0; //initialising num variable with 0
}
void print() {
cout<< num << endl; //output or print value of num variable on the output screen
}
void operator () (int val)
{
num+=val; //num=num+val
}
};
int main() {
A1 a; //object declaration
a.print(); // 0
a(2); //Functor
a.print(); //2
a(8); //function object or Functor
a.print() //10
return 0;
}
3) Lambda Expression
1- Anonymous notation representing something that performs calculation.
2- In Functional Programming ,it is used to produce first class and pure functions
3- This feature included in C++ 11.
3 Basic parts of
Lambda Expression
1. Capturing List: [ ]
2. Parameter List: ( )
3. Body : { }
Order of above basic parts is - [ ] ( ) { }
1. bool notZero(int e){return e!=0;}
myLambda=[ ] (int e != 0) return true; //myLambda receives an integer and returns bool or boolean value(true or false)