简体   繁体   中英

Overloading multiplication (addition, …) operator in function class

Sorry but I've got a complete noob-question. Have been trying to figure it out myself but I just can't seem to find the relevant information on google.

Let's put it like that, I have this piece of code:

class function
{
public:
    double (*f)(double x);
    function(double f(double x)): f(f){}
    double evalf(double x){
        return this->f(x);
    };
    function operator*(const function& other) const {
        return function(this->f*other.f);
    };
};

the problem is that the *-overload does not work and the issue is that he can't figure out how to multiply the two f's. Okay so here is what I did: I am calling the constructor using lambda expressions, for example

auto linear = [](double x){return x;};

and

auto blub = function(linear);

I figured out myself that

return function(this->f*other.f);

prolly won't work so what I tried was

auto mul = [&](double x){return this->f(x) * other.f(x);};
return function(mul);

but this ain't work either. Funny thing is it seems to work outside of the function-class.

auto mul = [](double x){return linear*linear;};

works just fine.

Does anyone have a solution for me ? Thanks in advance.

As you discovered yourself, to multiply you need to use a lambda, but a lambda with a caputure can't be converted to a function pointer. So for what you did here

 auto mul = [&](double x){return this->f(x) * other.f(x);}; return function(mul); 

to work, you need to change f to

std::function<double(double)> f

Together you end up with

class function
{
public:
    std::function<double(double)> f;

    function(std::function<double(double)> f): f(f){}
    double evalf(double x){
        return f(x);
    };
    function operator*(const function& other) const {
        return function( [=]( double x ){ return this->f(x) * other.f(x); } );
    };
};

which then works, see Live on coliru

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM