1
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

4
  • 6
    use std::array instead Commented Mar 29, 2022 at 17:58
  • how about AType SNr {0,0,9,0xFF}; ? Commented Mar 29, 2022 at 17:58
  • 2
    May i introduce you to current year C++? en.cppreference.com/w/cpp/container/array Commented Mar 29, 2022 at 18:08
  • Yes, @Taekahn: modern c++ is more than c + classes. Thanks. Commented Mar 29, 2022 at 19:17

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. BTW: The constructors do not need to be defined explicitly for this sample AType

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.