【问题标题】:compile-time evaluation of a function to compute a constant [duplicate]计算常数的函数的编译时评估
【发布时间】: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 的工作。尽管我尽了最大的努力在constexprconst 周围散布,但我仍然得到了

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 世纪!

【问题讨论】:

    标签: c++ constants constexpr


    【解决方案1】:

    实际上你已经非常接近你的目标了,如果你从kRed 中删除static,那么制作makeColor constexpr 就足够了

    Demo

    this answer 解释了为什么 static 有问题

    【讨论】:

    • 完美 - 谢谢。 (也感谢指向godbolt.org 的指针)
    • 乐于助人。 Matt Godbolt 的项目可能是近年来 c++ 社区发生的最好的事情:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2015-03-21
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多