struct rgb_color {
constexpr rgb_color(std::uint8_t nr, std::uint8_t ng, std::uint8_t nb) :
r(nr), g(ng), b(nb) { }
std::uint8_t r; // red
std::uint8_t g; // green
std::uint8_t b; // blue
constexpr static rgb_color black = rgb_color(0, 0, 0);
constexpr static rgb_color white = rgb_color(255, 255, 255);
};
constexpr static
常量定义编译失败:
constexpr variable cannot have non-literal type 'const rgb_color'
但是根据http://en.cppreference.com/w/cpp/concept/LiteralType , const rgb_color
应该是文字类型,因为它只有文字类型作为数据成员 (std::uint8_t
),而 constexpr
构造函数.
为什么代码编译不通过?
此外,是否有必要在.cc
文件中定义constexpr static
成员,例如
constexpr rgb_color rgb_color::black;
最佳答案
这行不通,因为您正在实例化一个尚未完全声明的类型(您还没有到达结束括号和分号,所以 rgb_color
仍然是一个不完整的类型)。
您可以通过在类之外声明您的常量来解决这个问题,也许在它们自己的命名空间中:
namespace rgb_color_constants {
constexpr static rgb_color black = rgb_color(0, 0, 0);
constexpr static rgb_color white = rgb_color(255, 255, 255);
}
关于c++ - 结构是非文字类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863503/