c++ - 结构是非文字类型

标签 c++ c++11 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 = 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/

相关文章:

c# - 将字符串数组从 C# 应用程序传递到 C++ DLL

c++ - 有效地从opencv转换数据

c++ - 在 constexpr 抛出的异常中使用副作用是否合法?

c++ - 在非 constexpr 函数上添加的 constexpr 限定符不会触发任何警告

c++ - 你可以有constexpr右值吗?

c++ - 我需要在新类中声明构造函数和析构函数吗?

c++ - 具有固定数量的模板参数的类内部的多个包扩展

c++ - 将仅移动函数参数传递给boost::thread构造函数

c++枚举类整数不适用于数组下标

c++ - Xcode 的 std::default_random_engine 的替代方案?