使用index而不是name来访问类成员变量

时间:2013-04-05 15:17:11

标签: c++ database templates

说我有课:

struct CAT
{
    //In order to simplify the problem, supposing the possible 
    // types of member variables are just int,double or string
    int a;
    double b;
    string c;
    int d;
    ....
};

就我而言,我必须编写一个函数,以便每个成员变量都可以使用其索引进行访问。

例如:

CAT cat;
setValue(cat,0,10);
setValue(cat,1,2.1);
setValue(cat,2,"hello");
setValue(cat,3,123);
//or
int i=1;
setValue(cat,i,2.1)

我想到的第一个想法是使用模板:

    template<typename T>
    void setValue(CAT &c, int idx, T value)
    {
          if (0 == idx){
              c.a = value;   //compile failure when using setValue(c,2,"hello")
          } else if( 1 == idx){  
              c.b = value;  
          } else if( 2 == idx){  
              c.b = value;   //compile failure when using setValue(c,0,10)
          }
          ...
    }

但由于代码中的注释,它不起作用。

有什么想法吗?

提前致谢。

修改:

我需要编写一个程序来将多个表及其记录转换为不同的c结构,例如: 表CAT,其架构为:

CAT(a,b,c,d,....)

转换为

struct S_CAT  //this is generate automatically by code
{
    int a;
    double b;
    string c;
    int d;
    ...
};

//automatically generate some code to write all records of table CAT to struct S_CAT

生成用于自动创建c结构的代码很容易,但很难生成将记录放入其中的代码。

1 个答案:

答案 0 :(得分:0)

您可以使用常规方法重载,或提供模板的几个特化:

void setValue(CAT &c, int idx, int value) {
    if (0 == idx) {
        c.a = value;
    } else if (3 == idx) {
        c.d = value;
    } else {
        Assert(false, "wrong type for index");
    }
}
void setValue(CAT &c, int idx, double value) {
    if (1 == idx) {
        c.b = value;
    } else {
        Assert(false, "wrong type for index");
    }
}
void setValue(CAT &c, int idx, string value) {
    if (2 == idx) {
        c.c = value;
    } else {
        Assert(false, "wrong type for index");
    }
}