[英]Statically initializing constexpr std::array of objects containing function pointers
我試圖用以下代碼靜態初始化包含函數指針的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(){}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.