类中的静态 constexpr 初始化链

static constexpr initialization chain within a class

本文关键字:初始化 constexpr 静态      更新时间:2023-10-16

我有一个常规类,我们称之为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();
};