65.9K
CodeProject 正在变化。 阅读更多。
Home

AGM::LibReflection:一个用于 C++ 的反射库。

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.97/5 (15投票s)

2004年11月2日

viewsIcon

146305

downloadIcon

1847

AGM::LibReflection 库的描述。

引言

LibReflection 是一个小型库(确切地说,是一个头文件),它为 C++ 类提供反射能力。当我们谈论反射时,我们不仅仅指 RTTI,而是指在日常编程中非常有用的丰富的功能。

  • 指定和检查类继承
  • 声明和检查普通字段和静态字段
  • 声明和检查普通方法、虚方法和静态方法
  • 声明和使用属性和事件
  • 设置和获取字段值
  • 调用方法并获取结果
  • 在没有头文件的情况下,通过使用类注册表创建实例

以上所有功能几乎都可以自动完成,程序员只需要在应用程序的类中放置很少量的宏...此外,您还可以获得类属性和事件的附加好处,这是 C++ 默认不提供的。

演示

使用 LibReflection 非常简单。以下代码片段显示了一个带有字段、属性和方法的类,所有这些都反映在类的 Class 对象中

//what you need to include
#include "reflection.hpp"


//namespace usage
using namespace agm::reflection;


//example base class
class Base {
public:
    //needed so as that the class gets reflection capabilities
    CLASS(Base, NullClass);

    //a reflected property
    PROPERTY(int, length);

    //a reflected method
    METHOD(public, bool, processLength, (int l));

private:
    //a reflected field
    FIELD(private, int, m_length);

    //property getter
    int get_length() const {
        return m_length;
    }

    //property setter
    void set_length(int l) {
        m_length = l;
    }
};


//a reflected method implementation
bool Base::processLength(int l)
{
    return l == m_length;
}


//a derived class
class Derived : public Base {
public:
    //derived reflected class
    CLASS(Derived, Base);
};


//for the demo
#include <iostream>
using namespace std;


int main()
{
    //a class instance
    Derived derived;

    //get the class of the Derived class
    const Class &derived_class = derived.getClass();

    //print the class name
    cout << derived_class.getName() << endl;

    //print the the m_length field
    const Field &length_field = derived_class.getField("m_length");
    cout << length_field.getType() << " " 
         << length_field.getName() << endl;

    //print the the length property
    const Property &length_prop = derived_class.getProperty("length");
    cout << length_prop.getType() << " " 
         << length_prop.getName() << endl;

    //print the 'processLength()' method
    const Method &process_length_method = 
                 derived_class.getMethod("processLength");
    cout << process_length_method.getType() << " "
         << process_length_method.getName()
         << process_length_method.getArgs()
         << endl;

    //set the length property
    cout << "using length property" << endl;
    length_prop.set(&derived, 10);
    int i;
    length_prop.get(i, &derived);
    cout << "length = " << i << endl;

    //calling the length method
    cout << "calling bool Base::processLength(int)" << endl;
    bool b;
    process_length_method.invoke(b, (Base *)&derived, 10);
    cout << "processLength=" << b << endl;

    getchar();
    return 0;
}

文档

有关更多信息,您可以查看我的小网站 这里

© . All rights reserved.