将成员函数从一个类连接到另一个类:没有匹配的成员函数来调用'connect'



我正在执行一项赋值,其中我必须将Display类的成员函数连接到Parent模板类。

parent.hpp头文件中,我有:

#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 */

注意,Parent是一个模板类,有几个参数类型为Args。在main.cpp中,我正在尝试执行以下操作:

#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;
}

其想法是,我正在尝试连接Display类中的showMessage()成员函数,该类在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 */

但是,当我尝试将showMessage()成员函数从Display连接到Parent时,此错误显示在myParent.connect( myDisplay.showMessage())的行:No matching member function for call to 'connect'。你知道为什么会发生这种事吗?

这里有两个问题:

  1. connect函数接受一个对象指针和一个成员函数指针,但您试图传递void函数的函数调用结果
  2. 成员函数指针指向一个非常数成员函数,但showMessage是一个常量成员函数

您可以通过修改connect的函数签名或重载函数并修改函数调用来修复此问题:

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);

最新更新