1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* EnumeratedArray is like Array, but indexed by a typed enum. */
9 #ifndef mozilla_EnumeratedArray_h
10 #define mozilla_EnumeratedArray_h
12 #include "mozilla/Array.h"
17 * EnumeratedArray is a fixed-size array container for use when an
18 * array is indexed by a specific enum class.
20 * This provides type safety by guarding at compile time against accidentally
21 * indexing such arrays with unrelated values. This also removes the need
22 * for manual casting when using a typed enum value to index arrays.
24 * Aside from the typing of indices, EnumeratedArray is similar to Array.
28 * enum class AnimalSpecies {
34 * EnumeratedArray<AnimalSpecies, AnimalSpecies::Count, int> headCount;
36 * headCount[AnimalSpecies::Cow] = 17;
37 * headCount[AnimalSpecies::Sheep] = 30;
40 template<typename IndexType
,
41 IndexType SizeAsEnumValue
,
46 static const size_t kSize
= size_t(SizeAsEnumValue
);
49 Array
<ValueType
, kSize
> mArray
;
54 explicit EnumeratedArray(const EnumeratedArray
& aOther
)
56 for (size_t i
= 0; i
< kSize
; i
++) {
57 mArray
[i
] = aOther
.mArray
[i
];
61 ValueType
& operator[](IndexType aIndex
)
63 return mArray
[size_t(aIndex
)];
66 const ValueType
& operator[](IndexType aIndex
) const
68 return mArray
[size_t(aIndex
)];
72 } // namespace mozilla
74 #endif // mozilla_EnumeratedArray_h