How to dynamically access structure fields?

Pages: 12
Oculus wrote:
Well, according to the current project, there is 17 tables of which only 12 will be actually used in the program. Is that many or not, I'm not sure, but definitely not as many as it could be. Either way, I'm not sure if overloading is okay for such amount. Any suggestions?

If the number of fields in each table is small, writing a struct for each table and overloading could still be good. If there are parts that are common among your tables (for example many tables have id and name mebmers) you could struct these up too.
Last edited on
Every single table has an id, but most of the other fields differ more or less. And speaking about the field count, there's a few tables that has more then 10 fields in it.
I guess you could somehow mix the two design approaches to fit your needs. You could add the option for a Table to be either dynamically built or hardcoded as a struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct SmallTable {/*...*/};
struct SmallerTable {/*...*/};
struct TinyTable {/*...*/};

class Table
{
public:

    enum Type
    {
        TT_SMALL,
        TT_SMALLER,
        TT_TINY
    };

private:

    //is hardcoded or not?
    bool hardcoded;

    //dynamic design data
    vector<FieldInfo> field_info;
    deque<Record> records;

    //hardcoded design data
    union record_type
    {
        SmallTable * small_t;
        SmallerTable * smaller_t;
        TinyTable * tiny_t;
    };

    deque<record_type> table;

    Type table_type;
};

But this complicates things more, since you now have to actually write two interfaces to interact with your tables. I really don't know if it's a good idea or not, just thought I should mention it is an option.

EDIT: Are containers of unions allowed?...

EDIT 2: Yes, they are!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <vector>
using namespace std;

union Type
{
    int i;
    double d;
    string * s;
};

int main()
{
    vector<Type> var_vec;

    var_vec.resize(2);
    var_vec[0].i=5;
    var_vec[1].s=new string;
    *(var_vec[1].s)="asdf";

    cout << var_vec[0].i << endl;
    cout << *(var_vec[1].s) << endl;

    delete var_vec[1].s;

    cout << "\nhit enter to quit";
    cin.get();
    return 0;
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12