class 中的静态 constexpr 初始化链
static constexpr initialization chain within a class
我有一个常规的 class,我们称它为 Handler
,它执行一些在运行时按需调用的算法。
该算法读取一个数组 (m_arr
),它的内容在编译时已知,所以我想利用 constexpr
来初始化它。
我不想要聚合初始化器(它可能看起来很难看),我想使用一个初始化数组的函数。
为了优雅和封装,我想将它们保留为 Handler
的静态成员。 m_arr
我想限定 constexpr
本身,因为我想用另一个基于它的函数初始化另一个数组(如果我首先成功使用这个)。
目前我正在为四个传播错误而苦苦挣扎。
这是我正在努力实现的草稿(标有错误):
#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)。
错误原因的解释(以及最接近的替代方法)非常感谢...
一般来说,classes 中的静态函数不能用于初始化constexpr
静态数据成员,因为在初始化时不考虑函数定义。您需要使其成为一个自由函数并在 class 主体中初始化数据成员:
constexpr std::array<int, SIZE> init()
{
// ...
}
struct C {
static constexpr std::array<int, SIZE> arr = init();
};
我有一个常规的 class,我们称它为 Handler
,它执行一些在运行时按需调用的算法。
该算法读取一个数组 (m_arr
),它的内容在编译时已知,所以我想利用 constexpr
来初始化它。
我不想要聚合初始化器(它可能看起来很难看),我想使用一个初始化数组的函数。
为了优雅和封装,我想将它们保留为 Handler
的静态成员。 m_arr
我想限定 constexpr
本身,因为我想用另一个基于它的函数初始化另一个数组(如果我首先成功使用这个)。
目前我正在为四个传播错误而苦苦挣扎。 这是我正在努力实现的草稿(标有错误):
#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)。
错误原因的解释(以及最接近的替代方法)非常感谢...
一般来说,classes 中的静态函数不能用于初始化constexpr
静态数据成员,因为在初始化时不考虑函数定义。您需要使其成为一个自由函数并在 class 主体中初始化数据成员:
constexpr std::array<int, SIZE> init()
{
// ...
}
struct C {
static constexpr std::array<int, SIZE> arr = init();
};