C++, can I statically initialize a std::map at compile time?(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
这篇关于C++,我可以在编译时静态初始化 std::map 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++,我可以在编译时静态初始化 std::map 吗?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01