Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize static const std::map during compile time?

Tags:

c++

c++11

stl

I have a look up table in my C++ program and for now I have to initialize it at the beginning of the program using something like this:

static const map<string, int> m;
m["a"] = 1;
m["b"] = 2;
...

I am just wondering if there is anyway I can make this initialization process happen at compile time rather than run time? I understand this has very small impact of performance to my program. I am just curious that with in the scope of current C++11/14/17 semantic it is possible or not.

like image 915
Bob Fang Avatar asked Jul 25 '17 13:07

Bob Fang


1 Answers

No, you can't initialize the std::map with data in compile time!

However, you can use this "fancier" initializer if you prefer, then you can have your data in a const std::map, in case this is what you are trying to do.

static const map<string, int> m = {
    { "a", 1 },
    { "b", 2 }
};

But AGAIN, this WILL NOT initialize the std::map itself in compile time. Behind the scenes, std::map will do the job in runtime.

like image 60
Wagner Patriota Avatar answered Oct 06 '22 23:10

Wagner Patriota