Chris
Chris

Reputation: 407

List member variable names in a class programmatically

Is it possible to list member variable names and their type programmatically? e.g:

class MyClass
{
public:
    MyClass();
    ~MyClass();
private:
    uint16_t    bob;
    uint8_t     dave;
    uint8_t     mick;
    int8_t     bazzer;    
};

I need to find (in code) what the variable names are and how big they are i.e. bob is a uint16_t. I understand that there is something in Java called 'reflection' and this seems to do what I want but I'm after something in straight up C++.

Upvotes: 2

Views: 861

Answers (1)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11492

No, there is no reflection in C++, what you want is not possible.

You can however make every class conforming to an interface defined you. Although this requires you to provide the information manually:

struct Foo
{
    uint16_t bar;
    char bar2;

    //maybe you want to return a typeid hash here instead of a string
    static std::map<std::string, std::string> GetMembers()
    {
        return {("bar", "uint16_t"), ("bar2", "char")}; 
    }
}

A code-generator could do this job for you by generating an AST and than inserting the above piece of code.

For a more advanced approach I would return a std::vector<MemberInfo> with MemberInfo being a class holding all relevant informations.

Such an approach could look like:

struct MemberInfo
{
    std::string m_name;
    size_t m_size;
};

template<typename T>
struct Reflection;

template<>
struct Reflection<Foo>
{  
   static std::vector<MemberInfo> GetMembers()
   {
       return {{"bar", sizeof(decltype(Foo::bar))}, {"bar2", sizeof(decltype(Foo::bar2))}}
   }
};

template<typename T>
void PrintMembers()
{
    for (auto& member : Reflection<T>::GetMembers())
    {
        std::cout << "name: " << member.m_name << " size: " << member.m_size << std::endl;
    }
}

Upvotes: 3

Related Questions