是否可以动态检查文本字符串是否是 C++ 中给定类的成员?

Is it possible to dynamically check if a string of text is a member inside of a given class in C++?

本文关键字:成员 C++ 是否是 动态 检查 字符串 文本 是否      更新时间:2023-10-16

我想知道是否有任何方法可以检查给定的类是否包含给定的成员,除了给定成员的名称作为 std::string 提供。以下是我所处的情况的一个例子:

class MyClass {
public:
int a;
int b;
int c;
void Handle_Class(std::string prop) {
if (this->prop) { //pseudo code of what I want to accomplish
//do stuff
};
};
} my_class;
int main() {
my_class.Handle_Class("a");
};

我知道Handle_Class不是像这样的函数的最佳名称,但它基本上应该检查类是否有一个名为 prop 的成员。 我不知道如何实际做到这一点。本质上,我正在尝试动态检查一个类是否具有给定的成员。 我在Lua方面有很多经验,你可以在Lua中轻松完成(虽然Lua不是面向对象的,但你可以使用表格来完成(

local my_table = {a = 123; b = 456; c = 789};
local function Handle_Table(prop)
if my_table[prop] then
print("property "..prop.." exists inside my_table!");
end
end

我将不胜感激任何帮助。 谢谢

还有一种方法可以在编译时使用模板执行此操作,您不能在运行时指定动态字符串进行检查,但请考虑:

如何检测类中是否存在特定成员变量?