C++ iostream, , ++.
In such a scenario, it is best to use a class template std::functioninstead of a function pointer syntax that is error prone.
#include <iostream>
#include <sstream>
#include <functional>
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
std::function<int(int,int)> minus = subtraction;
std::cout<<minus(5,4);
return 0;
}
Alternatively, if you still want to continue the function pointer, it is recommended to use typedefs
#include <iostream>
int subtraction(int a,int b){
return a-b;
}
typedef int (*MINUS)(int,int);
int main(int argc, const char * argv[])
{
MINUS minus = subtraction;
std::cout<<minus(5,4);
return 0;
}
And finally, another widely used option is the use of functors.
#include <iostream>
struct MINUS
{
int operator()(int a,int b){
return a-b;
}
};
int main(int argc, const char * argv[])
{
MINUS minus;
std::cout<<minus(5,4);
return 0;
}
source
share