Как реализовать плоскую карту с использованием массивов, когда ключи известны во время компиляции. Представьте, что я знаю свои ключи:
enum class Asset
{
FONT,
TEXTURE
};
struct AssetContainer
{
};
Следовательно, я мог бы сделать:
struct STATIC_DATA
{
inline static std::unordered_map<Asset, std::atomic<std::shared_ptr<const AssetContainer>>> ASSET_CACHE = {
{Asset::FONT, nullptr},
{Asset::TEXTURE, nullptr}
};
похоже, что, поскольку я знаю свои ключи и размер, я могу оптимизировать это, написав карту константного размера, используя массивы следующим образом:
template<class Key, class Value, size_t Size>
struct static_map
{
using container = std::array<std::pair<Key, Value>, Size>;
}
struct STATIC_DATA
{
inline static static_map<Asset, std::atomic<std::shared_ptr<const AssetContainer>>> ASSET_CACHE = {
{Asset::FONT, nullptr},
{Asset::TEXTURE, nullptr}
};
};
Компилятор не оптимизирует неупорядоченную карту в массив.
template<class Enum, class Value, std::size_t Count>
struct EnumMap:std::array<Count, Value> {
// Get the array out (base class):
constexpr std::array<Count, Value>& Array() { return *this; }
constexpr std::array<Count, Value> const& Array() const { return *this; }
// lookup in base (array):
constexpr Value& operator[]( Enum e ) {
return Array()[ static_cast<std::underlying_type_t<Enum>>(e) ];
}
// use non-const version and cast back to const:
constexpr Value const& operator[]( Enum e ) const {
return const_cast<Value const&>( const_cast<EnumMap&>(*this)[e] );
}
// Build from key-value pairs:
constexpr EnumMap( std::initializer_list<std::pair<Enum const, Value const>> il ) {
for (auto const&(key, value):il)
(*this)[key] = value;
}
};
это должно сделать это достаточно хорошо. Он без необходимости конструирует значения по умолчанию.
EnumMap<Asset, std::atomic<std::shared_ptr<const AssetContainer>>, 2> foo = {
{Asset::FONT, nullptr},
{Asset::TEXTURE, nullptr}
};
Пытаясь понять код, я удивился, что не смог с первого взгляда. Спасибо
Обратите внимание, что
Size
здесь действительно должен обозначать максимальные потенциальные индексы (количество значений в вашем перечисляемом классе), а не количество элементов на карте. Вы не можете получить это из списка инициализаторов.