How to assign struct values in a template class function?

  • A+
Category:Languages

I have a bunch of structures that I need to add to my vectors and give them some default values.

  1. Structures are external, I can not change them.
  2. While assigning these values, I need to see struct member names for convenience.
  3. I need to have all default values visually at the same place for convenience.
  4. Compiler currently optimizes away unused if branches in myClass::addStruct() - which is exactly what I want.

Q: can it be done in a better/simpler way?

EDIT I don't have C++17

// external structs

typedef struct A {     int member1;     float member2;     char *member3;     // ... } A;  typedef struct B {     double member5;     float member3;     int *member4;     // ... } B;  typedef struct C {     char* member5;     char* member2;     float *member3;     // ... } C;  ...  template <class T> void myClass::addStruct(std::vector<T> &vp) {     void *sp = nullptr;     if(std::is_same<T, A>::value) {         A s{};         s.member1 = 2;         s.member3 = "whatever";         sp = &s;     }     else if(std::is_same<T, B>::value) {         B s{};         s.member4 = nullptr;         s.member3 = 3.1f;         sp = &s;     }     else if(std::is_same<T, C>::value) {         C s{};         s.member2 = "whenever";         sp = &s;     } /*  else if() {     }     else if() {     } ... */      if(sp == nullptr) {         // print error         return;     }      vp.push_back(*(reinterpret_cast<T*>(sp))); }  // usage  addStruct<A>(...); addStruct<A>(...); addStruct<B>(...); addStruct<C>(...); 

 


  1. Code like this shouldn't even compile unless you use if constexpr (aka "static if"). It only "works" because you break the type system (the whole void* and reinterpret_cast dance). Type aliasing rules apply.
  2. You are taking the address of objects which have already gone out of scope. That's Undefined Behavior and while working now could break at any point when changing the code or compiler or just compiler version.
  3. If you really want to go with that code why wouldn't you just create non-template overloads for the different types? Way easier.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: