如何在 C++ 中获取类的成员变量列表? [英] How to get a list of a class's member variables in C++?

查看:128
本文介绍了如何在 C++ 中获取类的成员变量列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获得一个列表或者遍历一个类的每个成员变量的列表——不管它是什么类型.

Is there a way that I could obtain a list or maybe iterate through a list of each member variable of a class -regardless of it's type.

我的目的是将它们全部添加到模板 std::map 中.

My intention is to add them all to a template std::map.

class Person
{
    int Age;
    char *Name;
    template<typename Container> std::map<char *, Container> List;
    void MakeList()
    {
       for(auto i : Person.memberVariables)
       {
           List.emplace(i);
       }
    }
};

我可以做类似上面的事情来将我的类的每个变量添加到列表中,而不管其他代码有多不正确.添加到列表中是我感兴趣的.

Could I do something like the above to add each variable of my class to the list, regardless of how incorrect the other code is. The adding to the list is what I'm interested in.

提前致谢.

推荐答案

不,你不能用 C++ 来做.这称为 reflection,目前在 C++ 中不受支持.

No, you can't do it in C++. this is called reflection which is currently not supported in C++.

ISO C++ 委员会讨论了为 C++17 提议的编译时反射,它可以让您在编译时迭代类成员.但是这个特性需要很长时间才能标准化并在通用编译器上实现

The ISO C++ comitee talks about compile time reflection that is proposed for C++17 that will let you to iterate over class members on compile time. but it will take much time until this feature will be standarized and be implemented on the common compilers

作为旁注,我不明白为什么要遍历成员变量,然后可能实现序列化方法,在这种情况下,我需要类实现 serialize 方法和使用 SFINAE 强制执行.

as a side note, I don't see why one would want to iterate over member variables other then maybe implementing serialization method , which in this case I would require the class to implement serialize method and enforce it with SFINAE.

这篇关于如何在 C++ 中获取类的成员变量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆