-1

How can I use a member function of instantiate class as a function pointer ?

BEFORE :

main.cpp :

 void packetShower(data_t const& data) {
         // showing so data
   }

 ....

 // called with :
 std::shared_ptr<Net::ARawSocket> rawSock = std::make_shared<Net::LinuxRawSocket>(packetShower);

and It simply works. The packetShower function was a simple static method into my main.cpp

NOW :

I have a instantiate class Instance with a packetShower instance function

namespace App {
class Instance {
public:
    Instance() = default;
    ~Instance() = default;

    int run(int ac, char *av[]);
private:
    void init();

    void packetShower(data_t const& data)
  };
}

and, in my run() method, I try to create a function pointer to my packetShower function :

namespace App {

void Instance::init() {
 ...  
 }

void Instance::packetShower(data_t const& data) {
       .....
 }

int Instance::run(int argc, char** argv) {
   init(); 

   // and I tried : 

      void (Instance::*shower)(data_t const& data) = &Instance::packetShower; 

      std::shared_ptr<Net::ARawSocket> rawSock = std::make_shared<Net::LinuxRawSocket>(shower);


     // but It generate a big error

   }
 }

Any idea how I can do this ?

Thanks !

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
F4Ke
  • 1,631
  • 1
  • 20
  • 49
  • What type does `Net::LinuxRawSocket` ctor accepts? – Slava Nov 11 '16 at 18:22
  • the error I get is : `no matching function for call to ‘Net::LinuxRawSocket::LinuxRawSocket(void (App::Instance::**)(const std::vector&))’` But as I said, the "before" way of doing this wroked with a func pointer, but now I try to do that with a func pointer of a instance member – F4Ke Nov 11 '16 at 18:25
  • Can you read and comprehend my question? I can rephrase it. Can you provide definition of type that is accepted as callback in `Net::LinuxRawSocket` constructor? – Slava Nov 11 '16 at 18:26
  • If it worked with a free function, you are probably tripping over the hidden `this` parameter all methods have. Look into `std::bind` or get creative with lambda expressions. – user4581301 Nov 11 '16 at 18:28

1 Answers1

0

Declare packetShower as static and assign Instance::packetShower to shower.

If the function pointer is going to be used as a callback, the this pointer could be passed as user data and the declaration of packetShower would change as follows, if you were allowed to change the function declaration:

class Instance {
...
    static void packetShower(data_t const& data, void *userData) {
       Instance *i = (Instance)userData;
       ...
    }
...
};
Vivek
  • 320
  • 1
  • 5