【发布时间】:2011-02-14 15:58:56
【问题描述】:
是否可以以“通用”方式设置成员属性? 我还是 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() );
}
【问题讨论】:
-
你可以这样做。你只需要一个代码生成器来为你生成反射。