静态初始化包含功能指针的对象的constexpr std ::数组



我试图静态地初始化一个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(){}

我正在编译:

g++ -Wall -Wextra -Wshadow -Weffc++ -Wstrict-aliasing -ansi -pedantic -Werror -std=c++14 main.cpp

我很难理解我遇到的编译错误:

main.cpp:14:69: error: too many initializers for ‘const std::array<State, 10>’
 constexpr std::array<State, 10> states = {{OnEvent1}, {OnEvent2}}

编译器为G (Ubuntu 7.3.0-27ubuntu1〜18.04)7.3.0。

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

错误消息可能更好。但是,绊倒初始化实际上是您没有足够的牙套。回想一下std::array是包裹原始数组的聚合。因此,您需要这样初始化:

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

否则,某些不准确的支撑椭圆检测算法假定{OnEvent1}是初始化内部数组,而第二子句是冗余的。

现在您只需要为State提供默认的C'TOR,或调整数组大小。

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

#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(){}

最新更新