[英]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風格數組。
我想在編譯時這樣做
如果您接受C ++ 17解決方案(?),您可以使用std::array
的非const版本的operator[]
(從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
(important!)變量中
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' );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.