是否可以动态检查文本字符串是否是 C++ 中给定类的成员?
Is it possible to dynamically check if a string of text is a member inside of a given class in C++?
我想知道是否有任何方法可以检查给定的类是否包含给定的成员,除了给定成员的名称作为 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
我将不胜感激任何帮助。 谢谢
还有一种方法可以在编译时使用模板执行此操作,您不能在运行时指定动态字符串进行检查,但请考虑:
如何检测类中是否存在特定成员变量?
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗