Reputation: 87
I know this has been asked multiple times, most of the answers are difficult for me to understand. Could you please help me in figuring out what am I doing wrong ?
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <functional>
class A{
public:
A(double i){
_b = i;
}
double square(double i){
return i*i*_b;
}
private:
double _i;
double _b;
};
double cube(double (*objfunc)(double), double x){
return objfunc(x)*x;
}
int main()
{
double v = 2.0;
A a(v);
using std::placeholders::_1;
std::function<double(double)> f_square = std::bind( &A::square, &a, _1 );
double x = cube(f_square,3.0);
std::cout << " x = " << x << std::endl;
}
Thank you as always for your advice.
Given the class A and the cube function as they are how can I use the cube function in the main function ?
Update: Only way to do this would be to modify:
double cube(std::function<double(double)> objfunc, double x){
return objfunc(x)*x;
}
Upvotes: 0
Views: 72
Reputation: 10939
Make cube
take an std::function
object instead of a function pointer. Also get rid of the std::bind
and use a lambda together with the magic of auto
.
#include <iostream>
#include <functional>
class A
{
public:
A(double i) : _b(i) {}
double square(double i) { return i*i*_b; }
private:
double _b;
};
double cube(std::function<double(double)> objfunc, double x)
{
return objfunc(x)*x;
}
int main()
{
double v = 2.0;
A a(v);
auto f_square = [&a] ( double x ) { return a.square(x); };
double x = cube(f_square,3.0);
std::cout << " x = " << x << std::endl;
}
Upvotes: 2