Home > OS >  Initializing a c array with another one
Initializing a c array with another one

Time:03-30

struct AType {
  const byte data[4];
  AType(const byte d[]):data{d[0],d[1],d[2],d[3]} {}
  ...
};

const byte SERIALNR[4] = {0,0,9,0xFF};

AType SNr {SERIALNR};

This works, but I consider it a bit ugly. Is there a syntax with a shorter initializer list? And: How to do it, if that magic 4 were a template parameter?

The initialization of SERIALNR is just to make the sample complete, my goal is to implement something nice, allowing

AType SNr {SERIALNR}; or similar

And yes, that thing should be able to be constructed as const, if possible

CodePudding user response:

I think you can do this using a combination std::array and std::initializer_list. Also you can have the size of the array to be a template parameter:

using byte = unsigned char;

template <int S>
struct AType {
  std::array<byte, S> data;
  AType(const std::array<byte, S> &d) : data(d) {}
  AType(const std::initializer_list<byte> &d)  {
      std::copy(d.begin(), d.end(), data.begin());
  }
};

int main(){
  AType<4> SNr1 {0,0,9,0xFF}; // Uses the constructor with initializer_list as parameter
  AType<4> SNr2 {{0,0,9,0xFF}}; // Uses the constructor with std::array as parameter
  return 0;
}

Live example: https://godbolt.org/z/vjKbbr67G

  •  Tags:  
  • c
  • Related