【发布时间】:2019-12-18 13:30:48
【问题描述】:
灵感来自https://stackoverflow.com/a/37413361/1734357 我希望制作一个固定且已知大小的字符串颜色查找表,因此我不需要对其进行模板化,但字符串不是 constexpr
怎么办?
struct Colors
{
constexpr Colors() : colors()
{
for (size_t i = 0; i < 256; i++)
colors[i] = "0;" + to_string(i) + ";255";
for (size_t i = 0; i < 256; i++)
colors[256 + i] = "0;255;" + to_string(255 - i);
for (size_t i = 0; i < 256; i++)
colors[2 * 256 + i] = to_string(i) + ";255;0";
for (size_t i = 0; i < 256; i++)
colors[3 * 256 + i] = "255;" + to_string(255 - i) + ";0";
}
string colors[4*256];
};
【问题讨论】:
-
您不能将
std::string构造函数用于constexpr表达式。 -
std::string不是constexpr。 -
(
std::string_view是constexpr,但不确定这有多大帮助。) -
顺便说一句,为什么只有那些 1024 而不是所有的 16M?内存空间?
-
这是一个很好的解释 + 库在 C++11 中执行此操作(减去从 int 的转换):akrzemi1.wordpress.com/2017/06/28/…