gpt4 book ai didi

C++给定一个字符串列表,如何从一个类中获取相应的变量地址

转载 作者:行者123 更新时间:2023-11-28 01:37:21 24 4
gpt4 key购买 nike

我有课

class MyClass{
public:
int var_x;
int var_y;
int var_z;
}

然后是一个file.txt:

var_y
var_z

主要是想获取file.txt中每个变量的地址:

int main()
{
MyClass *obj;
obj = new MyClass();
std::vector<std::string>> varList = readFile("file.txt");

// I need generic code that would do the following:
// But the class can have any number (or named) variables
// And the text file can have any subset of the variables
std::cout << "var_y " << &(obj->var_y) << std::endl;
std::cout << "var_y " << &(obj->var_z) << std::endl;

delete obj;
return 0;

// Pseudo code would be
for var in varList:
addr = get_addr_from_string(var)
}

最佳答案

using Gettor = std::function< std::any(void*) > get_ptr;

template<class T>
struct ReflectedClass {
static std::unordered_map<std::string, Gettor> members;
template<class U>
static U* get( T* t, const char* name ) {
auto it = members.find(name);
if (it == members.end()) return nullptr;
std::any a = it->second( t );
U** ptr = std::any_cast<U*>(&a);
if (!ptr) return nullptr;
return *ptr;
}
};

#define TO_STR2(X) ##X
#define TO_STR(X) TO_STR2(X)
#define REFLECTED_MEMBER( CLASS, NAME ) \
ReflectedClass<CLASS>::members[ TO_STR(NAME) ] = \
[]( void* ptr )->std::any { \
return std::addressof( (CLASS*)(ptr)->NAME ); \
}

然后简单地做

REFLECTED_MEMBER(MyClass, var_x )
REFLECTED_MEMBER(MyClass, var_y )
REFLECTED_MEMBER(MyClass, var_z )

你可以调用

MyClass foo;
int* ptr = ReflectedClass<MyClass>::get<int>( &foo, "var_x" );

它返回指向 foo.var_x 的指针。

这是个坏主意,不要这样做。

关于C++给定一个字符串列表,如何从一个类中获取相应的变量地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48690917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com