Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make function which has function pointer as a parameter.

#include <iostream>
using namespace std;

class test{

public:
    test(){};

    double tt(double input){
        return input;
    };

};

double fptr_test(double (*fptr)(double), double input){
    return fptr(input);
}


int main(){

    test t;
    cout << t.tt(3) << endl;
    cout << fptr_test(t.tt, 3) << endl;  // This line doesn't work
    cout << fptr_test(&test::tt, 3) << endl;  // This line can't compile

    return 1;
}

But it doesn't work. How could I pass class member function as a parameter?

Can I call the member function without instantiation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
637 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to pass a pointer to a member-function, you need to use a member-function-pointer, not a pointer for generic free functions and an object to invoke it on.

Neither is optional.

double fptr_test(test& t, double (test::*fptr)(double), double input){
    return t.*fptr(input);
}

// call like this:
fptr_test(&test::tt, 3); // Your second try

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...