class constructor creating instance of arbitrary struct C++

Viewed 45

I want to make a class that creates an instance of an arbitrary struct and then has methods to write and load these structs from a file system. I currently do this with a macro that takes the name of the instance of the struct and saves and loads it. I wanted to instead create a class object that would wrap all of these together, but I don't know how to pass and use an arbitrary struct to the constructor.

I am limited to C++11. The code would work something like this

struct typeA{
   int age;
   int weight;
};

struct typeB{
    char name[10];
    int height;
};

class StructControl{
    public:
    void target;
    StructControl(void ITEM){
        ITEM target;
    }
    void S(void * addr,uint32_t size){
     //code for saving
    }
    void L(void * addr, unint32_t size){
     //code for loading
    }
    void Save(){
       S(&target,sizeof(target));
    }
    void Load(){
       L(&target,sizeof(target));
    }
};

void main(){
   StructControl myA(typeA);
   myA.target.age=45;
   myA.Save();
   StructControl myB(typeB);
   myB.height=110;
   myB.Save();
}
   
  
1 Answers

Thank you to the @TheUndeadFish and @PaulMcKenzie for pointing me towards templates.

#include <iostream>
#include <cmath>
#include <string>
#include <cstring>
#include <fstream>
#include <string.h>
#include <cstdint>
using namespace std;


struct typeA{
   int age=25;
   int weight=13;
};

struct typeB{
    char name[10];
    int height=55;
};

template <class TYPE>
class StructControl{
    public:
    TYPE target;
    char selfname[10];
    StructControl(const char * name){
        strcpy(selfname,name);
        printf("name:%s\n",selfname);

    }
    void Save(){
      printf("Saving object of size %lu to  addr:%p\n",sizeof(target),&target);
      //also save the struct to file
    }
    void Load(){
     printf("Loading object of size %lu to addr:%p\n",sizeof(target),&target);
      //also load the struct from file
    }
};
};

int main(){
   StructControl<typeA> myA("myA");
   printf("myA Age:%d\n",myA.target.age);
   myA.target.age=45;
   printf("myA Age:%d\n",myA.target.age);
   myA.Save();
   myA.Load();
   StructControl<typeB> myB("myB");
   printf("myB Height:%d\n",myB.target.height);
   myB.target.height=110;
   printf("myB Height:%d\n",myB.target.height);
   myB.Save();
   return 0;
}

OUTPUT:


name:myA
myA Age:25
myA Age:45
Saving object of size 8 to  addr:0x7fffbfb716b0
Loading object of size 8 to addr:0x7fffbfb716b0
name:myB
myB Height:55
myB Height:110
Saving object of size 16 to  addr:0x7fffbfb716d0
Related