#include <bits/stdc++.h>
using namespace std;
int add(int x, int y){return x+y;}
int sub(int x, int y){return x-y;}
int operation (int x, int y,int (*function)(int,int)){return function(x,y);}
int operation2(int x, int y,std::function<int(int, int)> function){return function(x,y);}
int main()
{
std::cout <<"Values 1 & 3. Pointer function: Add:"<<operation (1,3,&add)<<" Sub:"<<operation (1,3,&sub) << std::endl;
std::cout <<"Values 1 & 3. std::function : Add:"<<operation2(1,3,&add)<<" Sub:"<<operation2(1,3,&sub) << std::endl;
}
// C++ program to pass function as a
// pointer to any function
#include <iostream>
using namespace std;
// Function that add two numbers
int add(int x, int y)
{
return x + y;
}
// Function that multiplies two
// numbers
int multiply(int x, int y)
{
return x * y;
}
// Function that takes a pointer
// to a function
int invoke(int x, int y,
int (*func)(int, int))
{
return func(x, y);
}
// Driver Code
int main()
{
// Pass pointers to add & multiply
// function as required
cout << "Addition of 20 and 10 is ";
cout << invoke(20, 10, &add)
<< '
';
cout << "Multiplication of 20"
<< " and 10 is ";
cout << invoke(20, 10, &multiply)
<< '
';
return 0;
}
class MyClass
{
public:
MyClass();
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};
MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`
private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}