J. Hamme
J. Hamme

Reputation: 57

C++ brace initialization of struct with fixed size array member

Consider the following struct:

struct IPv6Address {
    uint8_t x[16];

    uint8_t& operator[](size_t pos) { return x[pos]; }
    uint8_t* bytes() { return x; }
}

static const IPv6Address WELL_KNOWN_ADDRESS =       //ff02::1
    {0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};

Brace initialization like this works fine. But once I add a constructor brace initialization doesn't work any more. I'd like to have this constructor in addition to brace initialization:

IPv6Address(uint8_t bytes[16]) { memcpy(x, bytes, sizeof(x)); }

Obviously no constructors are implicitly defined any more once I add my own constructor. But how can I redefine brace initialization in this case or force the compiler to create all default constructors?

Extra Requirement: I can't use the stdlib because I'm programming for an embedded application

Upvotes: 3

Views: 407

Answers (2)

dan
dan

Reputation: 333

You could simply use double braced lists with your existing constructor (when initialiter_list is not allowed)

static const IPv6Address WELL_KNOWN_ADDRESS =  
{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};

Upvotes: 2

Davide Spataro
Davide Spataro

Reputation: 7482

use a constructor with initializer_list

The following constructor should do the job (did not test it).

IPv6Address(std::initializer_list<uint8_t> c) : x{} {
  assert(c.size() <= std::size(x));
  std::copy(c.begin(), c.end(), x);
}

Upvotes: 1

Related Questions