C++ 静态初始化包含函数指针的constexpr std::对象数组

C++ 静态初始化包含函数指针的constexpr std::对象数组,c++,c++14,C++,C++14,我试图使用以下代码静态初始化包含函数指针的对象的constexpr std::数组: #include <array> using TVoidVoid = void(*)(void); class State{ public: constexpr State(TVoidVoid function) : function_{function}{} private: TVoidVoid function_; }; void OnEvent1(){} void OnEvent

我试图使用以下代码静态初始化包含函数指针的对象的constexpr std::数组:

#include <array>

using TVoidVoid = void(*)(void);

class State{
public:
  constexpr State(TVoidVoid function) : function_{function}{}
private:
  TVoidVoid function_;
};

void OnEvent1(){}
void OnEvent2(){}
constexpr std::array<State, 10> states = {{OnEvent1}, {OnEvent2}};

int main(){}
我无法理解我遇到的编译错误:

main.cpp:14:69: error: too many initializers for ‘const std::array<State, 10>’
 constexpr std::array<State, 10> states = {{OnEvent1}, {OnEvent2}}
main.cpp:14:69:错误:“const std::array”的初始值设定项太多
constexpr std::数组状态={{OnEvent1}、{OnEvent2}
编译器是g++(ubuntu7.3.0-27ubuntu1~18.04)7.3.0


这里有什么问题?非常感谢

您需要一个默认构造函数(用于最后8个)

#包括
使用TVoidVoid=void(*)(void);
阶级国家{
公众:
//此静态值相当于TVoidVoid
//由默认构造函数使用
静态void DefFunct(){}
constexpr状态(TVoidVoid函数):函数{function}{
//我们为
//使用我们的函数的数组的空元素
constexpr State():函数(DefFunct){}
私人:
TVoidVoid函数;
};
void OnEvent1(){}
void OnEvent2(){}
constexpr std::数组状态={OnEvent1,OnEvent2};
int main(){}

错误消息可能更好。但让初始化受挫的是,实际上您没有足够的大括号。回想一下,
std::array
是包装原始数组的聚合。所以您需要像这样初始化:

constexpr std::array<State, 10> states = {{ {OnEvent1}, {OnEvent2} }};
constexpr std::数组状态={{{OnEvent1},{OnEvent2}};
否则,有些不准确的括号省略检测算法假定
{OnEvent1}
是初始化内部数组,第二个子句是冗余的


现在您只需要为
状态提供一个默认的c'tor,或者调整数组大小。

谢谢Mirko,我重新表述了这个问题,但代码保持不变:我需要一个包含函数指针的对象数组。我想在数组中就地构造这些State类型的对象。@MihaiGalos编辑了答案。因此,其余的项需要默认构造,这会产生错误。当然所有元素都是静态构造的。令人惊叹的。请删除第一个答案,并在编辑后保留该答案,或者添加一些注释说明为什么需要这样做。那么我们就可以结束这个问题了!非常感谢!非常感谢。我不知道非默认初始化元素需要默认构造函数。@Mihai-每个构造函数都是初始化类对象的不同方式。前两个不需要它。剩下的就是了。您也可以用另一种方式提供它<代码> tVoIDValueStase= NulLPTR< /Calp>会使你现有的C.Tor也可用作默认的C.Tor。我有点惊讶,额外的{}(SturyTeleReq)和更少的{}也起作用(我的答案),但是原始的数量没有。米尔科@ C++中的初始化是疯狂的,可悲的是。
#include <array>

using TVoidVoid = void(*)(void);

class State{
public:
  // This static is equivalent to a TVoidVoid
  // used by the default constructor
  static void DefFunct() {}

  constexpr State(TVoidVoid function) : function_{function}{}

  // We create a default constructor for the 
  // empty elemnts of the array with our function
  constexpr State() : function_(DefFunct) {}

private:
  TVoidVoid function_;
};

void OnEvent1(){}
void OnEvent2(){}
constexpr std::array<State, 10> states = {OnEvent1, OnEvent2};

int main(){}
constexpr std::array<State, 10> states = {{ {OnEvent1}, {OnEvent2} }};