我正在执行一项赋值,其中我必须将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'
。你知道为什么会发生这种事吗?
这里有两个问题:
connect
函数接受一个对象指针和一个成员函数指针,但您试图传递void
函数的函数调用结果- 成员函数指针指向一个非常数成员函数,但
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);