【发布时间】:2017-01-01 01:17:18
【问题描述】:
序言:我查看了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 世纪!
【问题讨论】: