0

I found something about my problem, but I don't already understand very well. I need to do something like this:

class T
{
    double a;
public:
    double b;
    void setT(double par)
    {
        a = par;
    }

    double funct(double par1)
    {
        return par1 / a;
    } 

    void exec()
    {
        b = extfunct(funct, 10);
    }
};

double extfunct(double (*f)(double),double par2)
{
    return f(par2)+5;
}

Operation and function are only for example, but the structure is that. The reason of this structure is that I have a pre-built class which finds the minimum of a gived function (it's extfunct in the example). So I have to use it on a function member of a class. I understood the difference between pointer to function and pointer to member function, but I don't understand how to write it. Thanks, and sorry for the poor explanation of the problem.

2
  • Edit your question dont add information in the comments Commented Jul 1, 2013 at 16:11
  • Random semicolon lottery day... Commented Jul 1, 2013 at 16:11

1 Answer 1

1

Use a pointer to member function:

struct Foo
{
    void f(int, int) {}
    void g(int, int) {}

    void execute((Foo::*ptmf)(int, int), int a, int b)
    {
        // invoke
        (this->*ptmf)(a, b);
    }
};

Usage:

Foo x;
x.execute(&Foo::f, 1, 2);   // calls x.f(1, 2)
x.execute(&Foo::g, 2, 1);   // calls x.g(2, 1)

These pointers work as expected with virtual functions.

Sign up to request clarification or add additional context in comments.

7 Comments

There is a thing that I don't understand. In Usage you define Foo x; but I have to use it in a member internaly the class, in the function exec(). How I could do that.
@TommasoFerrari: It's all in the (this->*ptmf). The ->* is an operator. You could invoke the member function on any instance; I just chose this for this example.
Sorry but I don't understand. My function extfunct as an output double, I can't really find out how could be my function extfunct and the other exec. Sorry again, I'm trying to understand.
@TommasoFerrari: double extfunct((T::*ptfm)(double), double par2) { return (this->*ptmf)(par2) + 5; }
I have still some problems, I've done exactly what you write, but reports: "[Error] invalid use of 'this' in non-member function" in extfunct, if I make this a member it works!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.