Search code examples
c++function-pointers

Can not call function pointer of a struct to a class method


use C++98. I have a struct t_fd which is used inside a class MS. In the struct there are two pointers to function: fct_read, fct_write. I designed that the function pointers are pointing to the two methods of the class. But then I have this error when trying to call them.

expression preceding parentheses of apparent call must have (pointer-to-) function type.

Please advice on the error, also on the design. I need the two functions are methods of that class because I need to use class's attributes (even though it isn't showed here for the shake of simplicity). Thank you for your time, I appreciate your help!

#include <vector>
#include <iostream>

typedef struct  s_fd {
    void(MS::*fct_read) (int);
    void(MS::*fct_write) (int);
}   t_fd;

class MS
{
    private:
        std::vector< t_fd >            _fdSet;

        void        server_accept(int s)
        {
            if (s % 2 == 0)
                _fdSet[cs].fct_read = MS::client_read;
            else
                _fdSet[cs].fct_write = MS::client_write;
        }

        void        client_read(int fd)
        {
            std::cout << "I'm reading\n";
        }

        void        client_write(int fd)
        {
            std::cout << "I'm writing\n";
        }

        void        check_fd()
        {
            int i = 0;
            int size = 10;

            while (i < size)
            {
                if (i < 5)
                    _fdSet[i].fct_read(i); //Error here!
                if (i >= 5)
                    _fdSet[i].fct_write(i); //Error here!
                i++;
            }
        }
};


Solution

  • The intent of your code is difficult to understand (in its current form). But I would be happy to solve few issues in your code.

    1. MS class needs to be declared before you reference it the type from s_fd structure definition :
    class MS; // forward declaration
        
    typedef struct  s_fd {
    void(MS::* fct_read) (int);
    void(MS::* fct_write) (int);
    }   t_fd;
        
    class MS
    {  ... }
    
    1. the syntax to assign function pointer is incorrect. You forgot &:
    _fdSet[cs].fct_read = &MS::client_read;
    
    1. fct_read and fct_write are member function pointers. They should be applied on instance of MS class. In case you want to apply them on this object:
    if (i < 5) {
      auto fptr = _fdSet[i].fct_read;
      (this->*fptr)(i);
    }