Is it possible to implement a container that can hold a POD item and initialize while holding compile-time static stores?

For example, an object such as a map containing 20,000 records. Without calling the insert method at runtime, initialize its element at compile time and write this map to binary, just like a global int array.

+3


source to share


3 answers


Compile time: No
No runtime map::insert()

: Yes

Since C ++ 11, you can declare and initialize a global object.

#include<map>
std::map<int, int> m = {{0,0}, {1,1}, {2,2}};
int main () {}

      

Inside some global object constructor, you can write this map

to a file.



struct Global {
  Global (const char* fileName) {
    std::ofstream file(fileName);
    for(auto pair : m)
      // insert operation
  }
}
g_Initialize("xyz.txt");

      

Hence, you have things ready before launch main()

.

While doing this, beware of the static initialization order fiasco .

Update : std::map

- just a handy example. The key point here is use std::initializer_list

. You can also use your own class.

+5


source


To answer the question you asked in the title, "Yes, maybe."



See what you can do with constexpr

and templates. As far as writing it to a binary file, it's trickier. If you wanted this to be useful it wouldn't have to use any pointers. But anyway, it may not have been able to use dynamic memory allocation or pointers. No and stay constexpr

.

+2


source


A std::map

is just an ordered collection of pairs, and the same structure that you can initialize at compile time is the same.

Without considering the sorted property, you can simply declare an array with an initializer and hope you don't run into one of the implementation limits.

By ensuring that the item is sorted at compile time, it starts to get complicated and may not do well in practice. But somehow I doubt that this is part of your requirements. I think the "how" and "example" were probably not meant to do this, and if so, then you have your work to do: technically it's trivial, but do it by jotting down those thousands and thousands of lines and finally checking. you are within the implementation of the size of a static array, etc., will try to be patient.

0


source







All Articles