0

Apparently, designated initializers is not "correct" C++. Are there any alternatives for this?

I like the use of this for structs because:

  • Variables can be set optionally when creating the struct object.
  • The order of initializing doesn't matter.
  • Variables can be const.
  • This can be used in c++17 in combination with base classes.

Thanks Jelle

GuiGWR
  • 125
  • 1
  • 20

1 Answers1

1

Given

struct S {
    int x, y, z;
}:

S s {
    .y = 1; // not standard until C++20
};

Are there any alternatives for this?

You can use positional list initialisation:

S s{0, 1};

It has the drawback (arguably a benefit, depending on situation) that the member names are not explicit, meaning depends on order of members and all members preceding the last explicitly initialised must also be there.

Another alternative: Assign the member later.

S s{};
s.y = 1;

This has the drawback that it cannot be used to initialize const members. Another drawback is that this is not a single initialisation-expression. That can be worked around by using a function:

S init(int y) {
    S s{};
    s.y = y;
    return s;
}
S s = init(1);

Yet another alternative: Use a constructor.

struct S {
    int x = 0, y = 0, z = 0;
    S(int y): y(y) {}
};

This can be much simpler in some cases, but not at all clear in others (such as this vector-like case). Another drawback is the lack of trivial constructor.

eerorika
  • 232,697
  • 12
  • 197
  • 326