1

是否可以以“通用”方式设置成员属性?我还是 C++ 的新手,只是潜入了模板,如果这是要走的路吗?

我必须使用的类有大约 20 个要从 informix 数据库填充的字符串成员,我可以循环使用字段(=属性)名称的数组。

假设我有一个简单的课程

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

我可以这样使用它:

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"

我在循环中调用的方法可能看起来像这样......

// 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() );
}
4

3 回答 3

2

您可以使用成员数据指针。这些可以是任何类型-例如

struct x {
    int y;
    int z;
};

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

但是,如果您想在运行时通过标识符开始访问它们,则必须从头开始构建自己的系统。

于 2011-02-14T16:13:50.843 回答
1

我能想到的唯一选择是将您的属性存储在boost::any的映射中。假设您希望您的属性是异构类型。

基本思想是用 map 替换 Foo 中的属性。因此,您将拥有一个包装它们的地图,而不是拥有所有私有属性。C++ 的问题在于编译程序后您的属性名称不存在(与其他脚本语言如 python 不同)。因此,如果不使用某种数据结构,就无法从表示其名称的字符串中访问属性变量

删除旧编辑_

于 2011-02-14T16:03:23.937 回答
0

您可以使用 std::map。'ki' 的(基)类必须像这样实现 setattribute:

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

void MyClass::setattribute( const char * name, const char * value )
{
  mProps[name] = value;
} 
于 2011-02-14T16:05:38.960 回答