Skip to content

Commit 58f6502

Browse files
committed
C++ Practices: Prefer std::initializer_list instead of std::array
1 parent 9b41c1d commit 58f6502

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

bestpractices/c++practices.md

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ Item martha { "Martha", 30 };
576576
Item george { "George", 40 };
577577
```
578578
579-
Move the data into a container e.g. `constexpr std::array`, not a vector or map.
579+
Move the data into a container e.g. `constexpr std::initializer_list`, not a vector or map.
580580
581581
Container elements are typically value, array, pair, tuple, or a defined struct.
582582
Pair and tuple should only be used for very short lived data, such as this case:
@@ -585,13 +585,11 @@ Pair and tuple should only be used for very short lived data, such as this case:
585585
```cpp
586586
using Pair = std::pair<std::string_view, size_t>;
587587
588-
constexpr auto numItems {3};
589-
590-
constexpr std::array<Pair, numItems> items {{
588+
constexpr std::initializer_list<Pair> items {
591589
{ "Fred", 20 },
592590
{ "Martha", 30 },
593591
{ "George", 40 }
594-
}};
592+
};
595593
```
596594
{% endraw %}
597595
@@ -604,13 +602,11 @@ struct Button {
604602
size_t width;
605603
};
606604
607-
constexpr auto numButtons {3};
608-
609-
constexpr std::array<Button, numButtons> buttonDefs {{
605+
constexpr std::initializer_list<Button> buttonDefs {
610606
{ "Go", 25, 25 },
611607
{ "Get set", 20, 20 },
612608
{ "On your marks", 15, 15 }
613-
}};
609+
};
614610
```
615611
{% endraw %}
616612
When in doubt, use a struct - it is better to have good names than not.

0 commit comments

Comments
 (0)