在编译时使用枚举作为索引分配数组的值 (C++)

Assign array's values at compile time with and enum as index (C++)

我正在尝试通过枚举使用 C 样式数组作为映射,但我无法按部分初始化数组...我将通过代码更好地解释自己:
我有类似的东西:

enum Objects{CAR = 0, PLANE, BOY};

我有:

static const char* texturePaths[] = {"..\car.png", "..\plane.png", "..\boy.png"};

这确实按照我想要的方式工作,即

initTexture(texturePaths[CAR]);

但在这种情况下,我必须确保我以相同的顺序声明枚举和数组。 我想做这样的事情:

enum Objects{CAR = 0, PLANE, BOY, size};
const char* texturePaths[Objects::size];
texturePaths[BOY] = "..\boy.png";
texturePAths[CAR] = "..\car.png";
...

我知道这可行,但我需要在一个函数内完成并调用它,所以 运行 时间。我想在编译时做,因为有永远不会改变的常数值,在 运行 时间做它是一种浪费。
我也知道 constexpr 可以通过 lambda 函数来完成,但我不知道该怎么做

您标记了 constexpr,因此您可以使用 C++11 或更新版本,因此您可以使用 std::array。 一般建议:尽可能使用 std::array,而不是旧的 C 风格数组。

I want to so it at compile time

如果您接受 C++17 解决方案(?),您可以使用 std::arrayoperator[] 的非常量版本是(从 C++17 开始)constexpr.

因此您可以创建一个 constexpr 函数来根据需要初始化 std::array

enum Objects{CAR = 0, PLANE, BOY, size};

constexpr auto getTexturePath ()
 {
   std::array<char const *, Objects::size>  ret {{}};

   ret[BOY] = "..\boy.png";
   ret[CAR] = "..\car.png";
   // ...

   return ret;
 }

并将结果保存在 constexpr(重要!)变量中

   constexpr auto texturePath { getTexturePath() };

以下是一个完整的 C++17 编译示例,其中一些 static_assert() 证明 texturePath 的初始化是在编译时完成的。

#include <array>
#include <type_traits>

enum Objects{CAR = 0, PLANE, BOY, size};

constexpr auto getTexturePath ()
 {
   std::array<char const *, Objects::size>  ret {{}};

   ret[BOY] = "..\boy.png";
   ret[CAR] = "..\car.png";
   // ...

   return ret;
 }

int main()
 {
   constexpr auto texturePath { getTexturePath() };

   static_assert( texturePath[CAR][3] == 'c' ); 
   static_assert( texturePath[CAR][4] == 'a' ); 
   static_assert( texturePath[CAR][5] == 'r' ); 
 }