If you can use C++11, them lambda functions are your friend:
#include <functional>
#include <iostream>
std::function<double(double)> identity(std::function<double(double)> fn)
{
return [fn](double x){
// Do your logic here
return fn(x);
};
}
double sqr(double x) { return x * x; }
int main() {
auto f = identity(sqr);
std::cout << "sqr(100) = " << f(100) << std::endl;
}
If you don't plan to support C++11, you can do this way:
#include <iostream>
typedef double (*func_t)(double);
struct func
{
func_t fn;
double (*calc)(func_t, double);
double operator()(double x) {return calc(fn, x);}
};
double identity_calc(func_t fn, double x) {return fn(x);}
func identity(func_t fn)
{
func f = {fn, identity_calc};
return f;
}
double sqr(double x) { return x * x; }
int main() {
func f = identity(sqr);
std::cout << "sqr(100) = " << f(100) << std::endl;
}
But I don't think you will have much luck with plain C.