access members by string name

G

Gernot Frisch

Hi,

assume you have a class with members (or member get/set functions) and want
to call them by a string name with the least code to maintain.

I like to just have one macro line per member. The class should have a
working assignment operator.

The end class should look like:

class foo
{
int bar;
int goo;

public:
....
int GetGoo()const {return goo;}
void SetGoo(int g) {goo = g;}
....

std::map<std::string, something_to_map_the_GET_function> getfunctions;

static std::string GetAllParams() {return std::string("bar,goo");}
int GetVar(std::string name) {return getfunctions[name] () ; }
};
 
G

Gernot Frisch

class foo {
std::map<std::string, int> data_;

It's a slight overhead, but it works properly for what I want. It's obvious,
but I was unable to see. Thanks for opening my eyes.
 
M

Michael DOUBEZ

Hi,

assume you have a class with members (or member get/set functions) and want
to call them by a string name with the least code to maintain.

I like to just have one macro line per member. The class should have a
working assignment operator.

The end class should look like:

class foo
{
int bar;
int goo;

public:
...
int GetGoo()const {return goo;}
void SetGoo(int g) {goo = g;}
...

std::map<std::string, something_to_map_the_GET_function> getfunctions;

static std::string GetAllParams() {return std::string("bar,goo");}

// type for pointer to foo's member that is accessible.
typedef int (foo::*accessible_member_ptr);

static std::map<std::string,accessible_member_ptr> member_ptr;

static accessible_member_ptr
getfunctions(std::string name)
{
std::map<std::string,accessible_member_ptr>::iterator it =
member_ptr.find(name);
if( name == member_ptr.end() ) throw ParamDoesNotExists(name);

return it->second;
}

int GetVar(std::string name)
{
return this->*getfunctions(name);
}
int SetVar(std::string name, int newValue)
{
this->*getfunctions(name) = newValue;
}

};

// somewhere
member_ptr["bar"] = &foo::bar;
member_ptr["goo"] = &foo::goo;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top