C++反射的实现

#ifndef CLASSFACTORY_H
#define CLASSFACTORY_H

#define REFISTERFUNPTRBV(className)  typedef bool (className::*PTRFunctionB)(void)
#define REFISTERFUNPTRBP(className,parameterType)  typedef bool (className::*PTRFunctionBP)(parameterType*)

//Register.h

//ClassFactory.h

#include <string>
#include <map>
//工厂类的定义
template  <class CN, class FN >//CN为类型,FN定义的函数指针类型
class ClassFactory {
private:
    std::map<std::string, FN> m_FunctionMap;
public:

    //注册方法(可以注册构造方法,从而达到通过类名获取到对象的功能)
    void registFunction(std::string name, FN method)
    {
        m_FunctionMap.insert(make_pair(name, method));
    }

    //获取方法
    FN getFunctionByName(std::string functionName)
    {
        return m_FunctionMap.at(functionName);
    }

    //执行无参方法
    bool executeFunctionByName(std::string functionName,CN* object)
    {
        if(!object)return false;
        FN iter = m_FunctionMap.at(functionName);
        if (!iter)
        {
            return false;
        }else{
             return (object->*iter)();
        }
    }
};
#endif // CLASSFACTORY_H

使用(例子为QT的例子)

#include "widget.h"
#include "ui_widget.h"
#include <QString>
#include "ClassFactory.h"
//定义函数指针数据类型,可以手动定义
REFISTERFUNPTRBV(QWidget);
REFISTERFUNPTRBP(QWidget,int);
//REFISTERFUNPTRBP(wi,int);
//typedef bool (wi::*PTRFunctionBP)(int*);
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::test1()
{
    ui->textEdit->append("123");
}

void Widget::test2(int* i)
{
    ui->textEdit->append(QString::number(*i));
}



void Widget::on_pushButton_clicked()
{

//        注册本类中的方法
    ClassFactory<Widget,PTRFunctionB>  factory;
    factory.registFunction("test1",(PTRFunctionB)(&Widget::test1));
    PTRFunctionB b = factory.getFunctionByName("test1");
//    (this->*b)();
    factory.executeFunctionByName("test1",this);

    ClassFactory<Widget,PTRFunctionBP>  factory2;
    factory2.registFunction("test2",(PTRFunctionBP)(&Widget::test2));
    PTRFunctionBP bp = factory2.getFunctionByName("test2");
    int i = 9;
    (this->*bp)(&i);




/**
    //注册其他类中的方法
    wi w;
    ClassFactory<wi,PTRFunctionBP>  factory3;
    factory3.registFunction("test3",(PTRFunctionBP)(&wi::test3));
    PTRFunctionBP bp = factory3.getFunctionByName("test3");
     int i = 9;
    int k = ((&w)->*bp)(&i);
    ui->textEdit->append(QString::number(k));
*/
}

看完代码应该会发现,一个ClassFactory对象只能存放一种类型的函数指针,这里可以使用多态,将需要注册的类继承自某个父类,这样就可以扩展了;如果想注册后能全局使用,那就需要一个全局的注册对象。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值