非常量类中的constexpr初始化链

问题描述 投票:1回答:1

我有一个普通的类,我们称它为Handler,它执行一些在运行时按需调用的算法。该算法读取一个数组(m_arr),其内容在编译时是已知的,因此我想利用constexpr对其进行初始化。

我不需要聚合初始化程序(看起来很丑陋),我想使用一个函数来初始化数组。为了优雅起见,我希望将它们保留为Handler的静态成员。 m_arr我想限定constexpr本身,因为我想用另一个基于它的函数来初始化另一个数组(如果我首先成功实现了这个功能)。

目前,我正面临着四个传播错误。这是我要实现的目标的草案(带有错误标记):

//Handler.h:
#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...
};

//Handler.cpp:
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)。

非常感谢我的错误解释(以及最接近的工作替代方案...

c++ static initialization constexpr
1个回答
0
投票

通常来说,类中的静态函数不能用于初始化constexpr静态数据成员,因为在初始化时不考虑函数定义。您需要使其成为一个自由函数,并在类主体中初始化数据成员:

constexpr std::array<int, SIZE> init()
{
    // ...
}

struct C {
    static constexpr std::array<int, SIZE> arr = init();
};
© www.soinside.com 2019 - 2024. All rights reserved.