assign a member function to a function pointer

前端 未结 3 534
小鲜肉
小鲜肉 2021-01-27 22:44

If I have two classes like this :

class A
{
    public:
        int *(*fun)( const int &t );
        A( int *( *f )( const int &t ) ) : fun( f ) {}
};
         


        
相关标签:
3条回答
  • 2021-01-27 22:56

    this result in compiler error

    Because f is a A's non-static member function returning int*, that accepts single const reference to int. That means, that its type is not:

    int* (*)(const int &);
    

    but:

    int* (A::*)(const int&);
    

    Also, your code signalizes very bad design - I think you need simple virtual function. But if you want to keep writing things this way, you may want to read: ISOCPP: Pointers to members.

    Remember, that non-static member functions of type C always accepts additional implicit argument of type C* (or const C*, if function is declared with const qualifier), that points to instance of C this function was called on.

    0 讨论(0)
  • 2021-01-27 23:09

    Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the std::function. It only has been available since C++11. If you cannot use it, try looking on Boost's Implementation.

    I can give you an example of how to use the std::function:

    bool MyFunction(int i)
    {
        return i > 0;
    }
    
    std::function<bool(int)> funcPointer = MyFunction;
    

    Using this you will drastically improve your code reliability. As of your problem, specifically:

    class A
    {
    public:
        std::function<int*(const int&)> fun;
        A(std::function<int*(const int&)> f) : fun(f) {}
    };
    
    class B
    {
    private:
        float r;
        int *f(const int &t)
        {
            return new int(int(r) + t);
        }
        A *a;
        B()
        {
    
            std::function<int*(const int&)> tempFun = std::bind(&B::f, this, _1);
            a = new A(tempFun);
        }
    };
    

    You have to add the following namespace:

    using namespace std::placeholders;
    
    0 讨论(0)
  • 2021-01-27 23:17

    So what to do

    Not much. Other than templating A on the type of objects for which it will hold a pointer to a member function taking a reference to a const int and returning a pointer to int.

    What you're trying to do is to mix a pointer to a free function with a pointer to member function. Whilst it sounds like they're both function pointers they're different enough to not be able to pass through the same type definition.

    0 讨论(0)
提交回复
热议问题