Is it possible to implement a container that can hold a POD item and initialize while holding compile-time static stores?
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.
source to share
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
.
source to share
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.
source to share