C++ 中庞大但恒定的字典应使用哪种数据结构?
我必须使用带有整数(或枚举)键和字符串值的巨大字典。但这是完全恒定的。无法在运行时更改。有没有一种方法(使用模板等)在编译时检索字典数据而不是使用现有的字典结构?
I have to use a huge dictionary with integer (or enum) keys and string values. But this is totally constant. No way to change in runtime. Is there a way (using templates etc.) to retrieve dictionary data at compile time instead of using existing dictionary structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Clang 和 LLVM 通过结合使用代码生成和预处理器技巧来生成包含其对象的表,从而解决了您的问题。
您可以跳过任一步骤,具体取决于您自己的设置。例如:
现在,您可以生成枚举:
在 Clang 和 LLVM 中,代码生成阶段用于从更愉快的定义文件生成 .inc。
它工作得很好......但请注意,对枚举的任何修改都意味着完全重新编译。您可能希望采用“代码集”方法,其中枚举在内部使用但绝不会泄露到外部,并且向客户端提供稳定值(枚举的值)(
无符号
),以便旧客户端无需重新编译即可链接到新库:它们将被限制使用旧的代码集,如果它稳定的话,这没有问题。Clang and LLVM have solved your issue by generating tables containing their objects, using a combination of code generation and preprocessor trickery.
You can skip either step, depending on your own setup. For example:
Now, you can generate your enum:
In Clang and LLVM, a code generation phase is used to generate the .inc from more pleasant definition files.
It works pretty well... but do be aware that any modification of the enum implies full recompilation. You might wish to go to a "codeset" approach, where the enum is used internally but never leaked outside, and stable values (those of the enum) are provided to the client (
unsigned
), so that old clients can link to the new libraries without recompilation: they will be limited to use the old set of codes, which is no problem if it's stable.当然,您可以简单地使用 sed 将字典转换为由模板参数索引的字符串常量,并使用如下所示的头文件:
和具有多行形式的源文件:
另一方面,您真的想从维护角度?它需要对每个更改的字典条目和臃肿的可执行文件大小进行重新编译。
Surely you can simply use sed to transform the dictionary into a string constant indexed by template parameter, with a header file like:
and a source file with many lines of the form:
On the other hand, do you really want to do this from a maintenance perspective? It entails recompilation for every changed dictionary entry and bloated executable sizes.
自动代码生成怎么样?获取配置文件或数据库或任何源,并从中生成 C++ 头代码。它可能看起来像这样:
您可以使用简单的 bash 脚本或 ruby/python(如果您是受虐狂,则使用 C++)进行转换,这取决于配置文件的复杂性。
然后编写一些 make 规则,以便在配置文件更改时自动创建头文件。
How about automatic code generation? Take the configuration file or database or whatever the source is and generate C++ header code from that. It could look something like this:
You can do the conversion with a simple bash script or with ruby/python (or C++ if you are masochist), it depends on the complexity of your configuration file.
Then write some make rules to automatically create the header file(s) when the configuration file changes.