'Connecting a member function from one class to another class: No matching member function for call to 'connect'

I am doing an assignment where I have to connect a member function from the Display class to the Parent template class.

In the parent.hpp header file, I have:

#ifndef parent_hpp
#define parent_hpp

#include <iostream>
using namespace std;
#include <stdio.h>
#include <map>

template <typename... Args>
class Parent
{
   public:
      Parent();

      // Connect a member function to this Parent.
      template <typename T> int connect(T *inst, void (T::*func)(Args...));

      // Connect a std::function to this Parent.
      int connect(std::function<void(Args...)> const& slot);

      // Call all connected functions.
      void emit(Args... p);

};

#endif /* parent_hpp */

Note that Parent is a template class that several argument types Args. In the main.cpp, I am trying to do the following:

#include "parent.hpp"
#include "interface.hpp"
#include <iostream>

int main() {
   Display myDisplay; // Display initialization
   Parent<> myParent; // Parent initialization with no arguments
   myParent.connect( myDisplay.showMessage()); // Connect showMessage() to myParent
   
   return 0;
}

The idea is that I am trying to connect the showMessage() member function from Display class, which is defined in interface.hpp:

#ifndef interface_hpp
#define interface_hpp

#include <stdio.h>
#include "parent.hpp"

class Display
{
   public:
      inline void showMessage() const {
         std::cout << "Hey there, this is a test!" << std::endl;
      }
 };

 #endif /* interface_hpp */

However, when I am trying to connect the showMessage() member function from Display to Parent, this error shows up: No matching member function for call to 'connect' at the line of myParent.connect( myDisplay.showMessage()). Do you have any idea why this is happening?



Solution 1:[1]

There are 2 issues here:

  1. The connect function takes a object pointer and a member function pointer, but you're trying to pass the result of a function call of a void function.
  2. The member function pointer points to a non-const member function, but showMessage is a const member function.

You could fix this by modifying the function signature of connect or overloading the function, and modifying the function call:

template <typename... Args>
class Parent
{
   public:
   Parent();

   // Connect a member function to this Parent.
   template <typename T> int connect(T const* inst, void (T::*func)(Args...) const);

   // Connect a std::function to this Parent.
   int connect(std::function<void(Args...)> const& slot);

   // Call all connected functions.
   void emit(Args... p);

};
myParent.connect(&myDisplay, &Display::showMessage);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fabian