C++:创建初创公司之间的相关函子列表
我创建了类似函子列表(函数指针)的东西。然后我将它们以二进制形式写入文件。问题是,函子 - 是一个简单的函数指针。 (如果我错了,请纠正我。)但是函数的地址每次运行都不同。
那么,问题是 - 有什么方法可以创建始终相关的函子列表吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议使用某种配对数据结构,一侧带有标识符,另一侧带有函数指针。如果有足够的类似地图的东西:
您的应用程序应该在第一次需要时构建此地图并缓存结果。然后,当您“写入”指向文件的函数指针时,您应该写入唯一的 std::string 键。当应用程序“读取”函数指针时,它将读入键并将它们映射到程序调用的函数指针。
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:
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.
正如 @fbrereto 提到的,一种可能的解决方案是使用一些唯一标识符(整数、字符串、uuid 等)来标记不同的函子,该标识符不依赖于每个特定进程中的地址,并将这些键存储到文件中。然后,您可以使用工厂设计模式在读取文件时按需实例化函子。
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.