Class member function as function pointer

前端 未结 2 1602
温柔的废话
温柔的废话 2021-01-28 03:24

I have a class and one of its member functions is actually a function pointer. That way the user can overwrite what does this function do. I unfortunately have some difficulties

2条回答
  •  伪装坚强ぢ
    2021-01-28 03:45

    What you're trying to do isn't going to work. A pointer to a non-static member function is not the same as a pointer to a free function, because unlike the latter, the former must be invoked on an instance of the object. So you cannot declare a variable of one type and assign a pointer to a function of the other type to it.

    First, let's fix half your code:

    Since fcn_ptr is a pointer to member function, it's definition needs to be:

    double (Object::*fcn_ptr)(const double &) = NULL;
    

    Then, the cast in your constructor is invalid. You're attempting to cast a pointer to a member function to a pointer to a free function. Get rid of the cast.

    Object() : fcn_ptr(&Object::fcn_default)
    {}
    

    Finally, when you invoke fcn_ptr, you can't simply conjure it out of thin air. It is a data member of Object and so you need an instance of the class to access fcn_ptr. So call it as:

    (test1.*(test1.fcn_ptr))(2)
    

    Make all these changes, and half your code will compile and produce the correct result. Live demo


    The other half, where you try to assign a pointer to a free function to fcn_ptr still won't work because of the reasons stated earlier. The way to fix this is to use std::function instead of a function pointer.

    class Object{
        public:
            Object() : fcn_ptr(std::bind(&Object::fcn_default, this, std::placeholders::_1))
            {}
            std::function fcn_ptr;
    
        private:
            double fcn_default(const double &phit){
                return 3.2+phit;
            }
    };
    

    And then use it as:

    cout << (test1.fcn_ptr)(2) << endl;
    
    test2.fcn_ptr = &fcn_mod;
    cout << (test2.fcn_ptr)(2) << endl;
    

    Live demo

提交回复
热议问题