首页 > 解决方案 > 创建一个返回泛型成员函数指针的虚函数

问题描述

我想写一个COMMUNICATOR具有虚函数的抽象类get_func()

class COMMUNICATOR : public QObject{
public:
    virtual <what type???> get_func() = 0;
};

现在假设INT_SENDER, INT_RECEIVER, STR_SENDER, 并且STR_RECEIVER都派生自COMMUNICATOR。它们每个都提供了自己的 get_func() 实现,它们可以像这样使用:

COMMUNICATOR *int_sender = new INT_SENDER;
COMMUNICATOR *int_receiver = new INT_RECEIVER;

COMMUNICATOR *str_sender = new STR_SENDER;
COMMUNICATOR *str_receiver = new STR_RECEIVER;

//INT_SENDER::get_func() and INT_RECEIVER::get_func() both return a member function pointer of signature void(*)(int)
connect( int_sender, int_sender->get_func(), int_receiver, int_receiver->get_func() );

//STR_SENDER::get_func() and STR_RECEIVER::get_func() both return a member function pointer of signature void(*)(std::string)
connect( str_sender, str_sender->get_func(), str_receiver, str_receiver->get_func() );

我想通过这个设计实现的是:

(1) 为所有派生自 COMMUNICATOR 的类赋予相同的接口:get_func() 函数

(2) 使用 COMMUNICATOR 及其派生类不需要处理 get_func() 返回的函数的签名。相反,函数指针直接传递给 connect();

是否有某种 hack 来实现我想要的,比如让 get_func() 返回一些类型擦除包装对象,我可以从中将函数指针转储到 connect() 中?还是我在这里尝试不可能的事情?

标签: c++qtdesign-patternsc++14type-erasure

解决方案


推荐阅读