C++: create betwen-startups relevent functor list
I create something like a list of functors (functions pointers). Then I write them in binary form into file. The problem is, that, functor - is a simple function pointer. (correct me if I'm wrong.) But the address of function is different from one run to another.
So, the question - is there any way to create list of functors that will be relevant all the time开发者_如何学C?
I'd recommend some kind of paired data structure with an identifier on one side and the function pointer on the other. If there are enough of them something like a map:
typedef void (*fptr_t)(); // or whatever your function pointer type is
std::map<std::string, fptr_t> fptr_map;
Your application should build this map when it is first needed and cache the result. Then when you "write" the function pointers to a file, you should write the unique std::string keys instead. When the application "reads" the function pointers it will read in the keys and map them to the function pointers for that invocation of the program.
One possible solution, as @fbrereto mentions, is to label different functors with some unique identifier (integer, string, uuid, etc.), that does not depend on addresses in each particular process, and store these keys into the file. Then you can use something the Factory Design Pattern to instantiate functors on demand when reading the file.
Yes, function pointer is just an address. You can't rely on it. Instead you can create array of functors and store indexes of functors to file. or you can create hashtable and reference functors by name.
精彩评论