C ++,我可以在编译时静态初始化std :: map吗? [英] C++, can I statically initialize a std::map at compile time?

查看:2063
本文介绍了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.

但是,我很好奇 - 在编译时是否还要初始化map,vector等等?

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆