开发者

set a member attribute in a "generic" way

开发者 https://www.devze.com 2023-02-10 22:35 出处:网络
Is it possible to set a member attribute in a \"generic\" way? I am still new to c++and just dived into templates, if this is the way to go?

Is it possible to set a member attribute in a "generic" way? I am still new to c++ and just dived into templates, if this is the way to go?

The class i have to use has around 20 string members to be filled from informix database and i could loop through an array with the field(=attribute) names.

Let's say i have a simple class

class Foo
{
  public:
    attr1
    attr2
  Foo() { };
  ~Foo();
}

and i could use it like that:

Foo foo;

string myattr = "attr1";
string myval = "val x1";
string myval = "val x2";

setattribute( foo, myattr, myval1 );   // pseudocode... possible somehow?
cout << foo.attr1;     // prints "val x1"

setattribute( foo, myattr, myval2 );   // pseudocode... possible somehow?
cout << foo.attr1;     // prints "val x2"

The method i call in the loop could look like this...

// its_ref : empty string reference
// row: ptr on the current db row = query result object
// colname:  the db column = attribute
// ki: the object 

void get_fd( ITString & its_ref, ITRow * row, ITString colname, ns4__SOAPKunde& ki ) {
        ITConversions *c;
        ITValue *v = row->Column( colname );
        v->QueryInterface(ITConversionsIID, (void **) &c);
        c->ConvertTo( its_ref );
        // here is the开发者_开发百科 place i want to use it :
        setattribute( ki, colname, its_ref.Data() );
}


You can use member data pointers. These can be of any type- e.g.

struct x {
    int y;
    int z;
};

int main() {
    int x::* res = &x::y;
}

However, if you want to start accessing them by identifier at runtime, you will have to build your own system from scratch.


The only option I can think of would be to store you attributes in a map of boost::any. With the assumption that you want your attributes to be of heterogeneous types.

The basic idea is to replace your attributes in Foo with map. So instead of having all your private attributes you would have a map that wraps them. The problem with C++ is that your attribute names don't exist after compiling the program (unlike other scripted languages like python). So there is no way to access an attribute variable from a string representing it's name without using some kind of data structure

removed old edit_


You could use a std::map. The (base) class of 'ki' then has to implement setattribute like this:

// Member variable of MyClass
std::map<string, string> mProps;

void MyClass::setattribute( const char * name, const char * value )
{
  mProps[name] = value;
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号