查找类的成员变量及其类型的列表? [英] Find the list of member variables of a class and their types?

查看:77
本文介绍了查找类的成员变量及其类型的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有听说过这是可能的,但希望它可能。

对于具有比这更多的成员变量的类:

I haven't ever heard it's possible, but asking with the hope that it might.
For a class with many more member variables than this:

class A
{
 public:
  SomeOtherClass* s;
  int i;
  int j;
  A() {}
  A(const A& soc): s(soc.s->Clone()), i(soc.i), j(soc.j) {}
};



我总是要记住,如果我添加另一个变量 int k 到类,我还必须将它添加到初始化列表 k(soc.k),有时在析构函数中。
我不得不添加/删除成员变量这么多次,它真的很烦人忘记复制在初始化列表中,并在调试时发现更多的遗漏。

I always have to remember that if I add another variable int k to the class, I'll also have to add it in the initialization list k(soc.k) and sometimes in the destructor too. I've had to add/remove member variables so many times and it's really annoying to forget about the copying in the initialization list and finding the omission much much later while debugging.

因此,我想知道是否有一个语法/逻辑,通过它我可以找到一个类的成员变量及其类型的列表,这样我可以迭代通过它们,决定哪些需要在复制ctor中复制,哪些需要深度复制?

Therefore, I wanted to know if there's a syntax/logic through which I can find out the list of member variables of a class and their types, so that I can maybe iterate through them and decide which of them need to be copied in the copy ctor and which of them need to be deep copied?

我不明白为什么C ++的创建者不能包含这样的工具,因为除了虚拟成员之外,变量的内存位置将是连续的,类型也是知道的。即使它们是extern或virtual,类型和大小将在运行时知道。所以不应该有可能吗?

I don't see why the creators of C++ couldn't have included such a facility, since except for virtual members, the memory locations of variables would be contiguous and their types are known too. Even if they were extern or virtual, the type and size would be known at runtime. So shouldn't it be possible?

推荐答案

C ++没有反射,所以你需要一个外部库这个。 C ++的创建者没有实现此功能,因为它意味着性能损失,性能是C ++的主要目标之一。

There is no reflection in C++, so you'll need an external library to do this. The creators of C++ didn't implement this feature because it implies a performance penalty, and performance is one of C++'s main goals.

这篇关于查找类的成员变量及其类型的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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