tml*_*len 7 c++ constexpr c++11
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);
};
Run Code Online (Sandbox Code Playgroud)
该constexpr static常量定义无法编译:
constexpr variable cannot have non-literal type 'const rgb_color'
Run Code Online (Sandbox Code Playgroud)
但是根据http://en.cppreference.com/w/cpp/concept/LiteralType,const rgb_color应该是文字类型,因为它只有文字类型作为数据成员(std::uint8_t)和constexpr构造函数.
为什么代码不能编译?
此外,是否有必要constexpr static在.cc文件中定义成员,如
constexpr rgb_color rgb_color::black;
Run Code Online (Sandbox Code Playgroud)
rem*_*s4e 17
这不起作用,因为你正在实例化一个尚未完全声明的类型(你尚未到达右括号和分号,所以 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);
}
Run Code Online (Sandbox Code Playgroud)
您应该能够将blackandwhite放入static constexpr函数中——即,这是“命名构造函数习惯用法”的一个示例。
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() { return rgb_color(0, 0, 0); }
constexpr static rgb_color white() { return rgb_color(255, 255, 255); }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2510 次 |
| 最近记录: |