C++,我可以在编译时静态初始化 std::map 吗?
如果我编码这个
std::map<int, char> example = {
(1, 'a'),
(2, 'b'),
(3, 'c')
};
然后g++对我说
deducing from brace-enclosed initializer list requires #include <initializer_list>
in C++98 ‘example’ must be initialized by constructor, not by ‘{...}’
这让我有点恼火,因为构造函数是运行时的,理论上可能会失败.
and that annoys me slightly because the constructor is run-time and can, theoretically fail.
当然,如果确实如此,它会很快失败并且应该始终如一地这样做,因此我应该快速定位 &纠正问题.
Sure, if it does, it will fail quickly and ought to do so consistently, so that I ought to quickly locate & correct the problem.
但是,我仍然很好奇 - 有没有在编译时初始化地图、向量等?
But, still, I am curious - is there anyway to initialize map, vector, etc, at compile time?
我应该说我正在为嵌入式系统开发.并非所有处理器都有 C++0x 编译器.最流行的可能会,但我不想遇到陷阱&必须维护 2 个版本的代码.
I should have said that I am developing for embedded systems. Not all processors will have a C++0x compiler. The most popular probably will, but I don't want to encounter a gotcha & have to maintain 2 versions of the code.
至于 Boost,我还没有决定.他们对在嵌入式系统中使用他们的有限状态机类是一厢情愿的,所以这实际上是我在这里编码的,事件/状态/Fsm 类.
As to Boost, I am undecided. They are wishy-washy on the use of their Finite State Machine classes in embedded systems, so that is actually what I am coding here, Event/State/Fsm classes.
唉,我想我还是谨慎一点为好,但我希望这个讨论对其他人有所帮助.
Sigh, I guess I'd better just play it safe, but I hope that this discussion has been helpful for others.
推荐答案
不在 C++98 中.C++11 支持这一点,因此如果您启用 C++11 标志并包含 g++ 建议的内容,则可以.
Not in C++98. C++11 supports this, so if you enable C++11 flags and include what g++ suggests, you can.
从 gcc 5 C++11 默认开启
from gcc 5 C++11 is on by default
相关文章