C++,我可以在编译时静态初始化 std::map 吗?

2024-05-11C/C++开发问题
1

本文介绍了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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6