Pointer to variables from its name

Started by
7 comments, last by Dmnbp7ip 17 years, 1 month ago
Hi, I would like to know how I could get the pointer to a variable in a class, by only providing the name of the variable to the class. This variable could have any type… For example, I would like a function that would look like : void* GetPointerfromName(char*) Thank you !
Advertisement
if (name == "abc"){    return reinterpret_cast<void*>(&this->abc);}else if (name == "zzyy"){    return reinterpret_cast<void*>(&this->zzyy);}else ...

Thank you, but wouldn't be there a more generic implementation ?

I saw something like :
template <class T> T const * GetAddress(const T& value);

Any idea ??
What's the context? Can you describe in more detail what you're trying to do?
Yep,

I try to create a class of Interface between a dll and a program. I would like the program to get the address of any public variable inside a class of my dll only by giving its name. I want to be able to add or delete variables for programming without changing the function that calls the variables.

Actually, I don't even know if it is possible.
template<typename T>T* MyClass::GetPointerfromName(MyClass::*T var){    return &(this->*var);}int main(){    int* p = my_obj.GetPointerfromName(&MyClass::x);};
or
template<typename T>T* MyClass::GetPointerfromName(const std::string& name){    std::map<std::string, boost::any> name_map = boost::list_of_map_begin        ("abc", &MyClass::abc)        // .....        ("xyz", &MyClass::xyz);    std::map<std::string, boost::any>::iterator i = name_map.find(name);    if (i == name_map.end())    {        throw std::logic_error("Member does not exist");    }    return &(this->*(boost::any_cast<MyClass::*T>(*i)));}int main(){    int* p = my_obj.GetPointerfromName<int>("xyz");}
While this is an overkill, it is a somewhat interesting way to add reflection and run-time created classes.

http://www.vollmann.ch/en/pubs/meta/meta/meta.html

If anything, it at least makes for interesting reading.
The offsetof macro can do this, but this is probably not a good idea. Just pass around some sort of dictionary. Or, hell, if all you want is to not modify code that doesn't use the new parameter, but still needs to pass it on for some reason, pass a struct.
OK, thanks all. I will solve it with a kind of dictionary.

This topic is closed to new replies.

Advertisement