1

EDIT I am coding in c++11.

I have programs that I write for micro controllers that use a struct to store items in flash memory together. For example

struct save{
    char name[10]="bob";
    int weight=244;
    char food[50]="Taco";
} myVals;

I know that there is no built in way to iterate through struct values, but I figure I should be able to add some sort of container with reference to the struct values, but figuring out one that can take different types has been challenging for me. The best I've been able to do so far is a function to print them out, like below.

struct save{
    char name[10]="bob";
    int weight=244;
    char food[50]="Taco";
    function dump(){
        printf("{\"name\":\"%s\",\"weight\":%s,\"food\":\"%s\"}",name,weight,food);
    }
} myVals;

However, what I really want is an object I can iterate through. I realize there is no reflection in C++, but is there a way I can build it in to my struct? Is there a way to create some container like this where I just give it a list of types and a list of items?

mylist<char* ,int, char*> {name,weight,food}

EDIT

I tried using a tuple. I cannot use it inside the struct.

struct Data{
    char name[10]="bob";
    int weight=14;
    char food[50]="taco";
    int size=3;
    tuple<char*,int,char*> mylist (name,weight,food);
} data;

becuase I get errors like

error: ‘name’ is not a type

However, if I put it outside the struct it compiles and I can get values.

struct Data{
    char name[10]="bob";
    int weight=14;
    char food[50]="taco";
    int size=3;
} data;

tuple<char*,int,char*> mylist (data.name,data.weight,data.food);

int main(){
    printf("%s",get<0>(mylist));
    return 0;
}

>food

Unfortunately this doesn't really help as tuples are notoriously hard to iterate over.

jeffpkamp
  • 2,732
  • 2
  • 27
  • 51

0 Answers0