<分区>
序言:我看过 constexpr initializing static member using static function ,但是(感谢 Oleg Bogdanov 的回答)我没有尝试初始化静态。
我想知道如何进行以下工作:
typedef uint32_t color_t; // represent color as 00rrggbb
class Color {
static color_t makeColor(const uint8_t r,
const uint8_t g,
const uint8_t b) {
return (((color_t)r << 16) | ((color_t)g << 8) | (color_t)b);
}
static const color_t kRed = makeColor(255, 0, 0);
}
在我看来,编译器需要被告知它可以在编译时计算 makeColor()
,所以我认为这是 constexpr
的工作。尽管我尽最大努力围绕 constexpr
和 const
,我仍然得到
error: field initializer is not constant
我错过了什么?
P.S.: 我当然可以用#define 完成我想要的:
#define makeColor(r, g, b) (((color_t)(r) << 16) | ((color_t)(g) << 8) | (color_t)(b))
...但这似乎是 20 世纪的事!