类中的静态 constexpr 初始化链
static constexpr initialization chain within a class
我有一个常规类,我们称之为Handler
,它执行一些在运行时按需调用的算法。 该算法读取一个数组(m_arr
(,它的内容在编译时是已知的,所以我想利用constexpr
来初始化它。
我不想要聚合初始值设定项(它可能看起来很丑(,我想使用初始化数组的函数。 为了优雅和封装,我想将它们保留为Handler
的静态成员。我想限定constexpr
本身的m_arr
,因为我想使用另一个基于它的函数初始化另一个数组(如果我首先成功使用这个数组(。
目前,我正在努力解决四个传播错误。 这是我试图实现的目标的草稿(标记了错误(:
#include <array>
class Handler
{
static const int SIZE = 20;
static constexpr std::array<int, SIZE> initArr();
static constexpr std::array<int, SIZE> m_arr; //C2737 'private: static std::array<int, SIZE> const Handler::m_arr': 'constexpr' object must be initialized
//much other non-const stuff which this class handles...
};
constexpr std::array<int, Handler::SIZE> Handler::m_arr = Handler::initArr(); //C2131 expression did not evaluate to a constant
constexpr std::array<int, Handler::SIZE> Handler::initArr()
{
std::array<int, SIZE> arr; //C3250 'arr': declaration is not allowed in 'constexpr' function body
arr[0] = int(2); //C3249 illegal statement or sub-expression for 'constexpr' function
arr[1] = int(7); //C3249 illegal statement or sub-expression for 'constexpr' function
arr[2] = int(4); // -- || --
//...
return arr;
}
显然我在这里做错了什么 - 或者 - 我希望从语言中提供它无法提供的东西(编译器 - MSVC 2015/14.0(。
解释错误的原因(以及最接近的工作替代方案(非常非常感谢...
一般来说,类中的静态函数不能用于初始化静态数据成员constexpr
因为在初始化时不考虑函数定义。 您需要使其成为一个自由函数,并在类体中初始化数据成员:
constexpr std::array<int, SIZE> init()
{
// ...
}
struct C {
static constexpr std::array<int, SIZE> arr = init();
};
相关文章:
- 多成员Constexpr结构初始化
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 使用 std::分配器在 constexpr 中进行默认初始化
- C++:初始化 constexpr 构造函数中的成员数组
- 初始化模板化类中的静态 constexpr 成员
- 在 constexpr 构造函数中初始化数组是否合法?
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 静态 constexpr 成员变量初始化
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 正在初始化函数指针的constexpr数组
- 使用 constinit 变量初始化 constexpr 变量
- 这是通过初始化 constexpr 变量来标记编译错误的合理跳转
- 是否可以以编程方式初始化 constexpr std::array 成员
- 使用模板函数初始化 constexpr 数组
- 如何编写工厂功能以在C 中初始化constexpr参考
- 现代C++:初始化 constexpr 表
- 为什么我不能使用 constexpr 全局变量来初始化 constexpr 引用类型
- 使用const初始化constexpr,--int vs float
- 在MSVC和GCC上声明和初始化constexpr的通用语法