在C++中用于巨大但常量字典的数据结构

Gul*_*han 5 c++ dictionary constants data-structures

我必须使用带有整数(或枚举)键和字符串值的庞大字典.但这完全不变.无法在运行时更改.有没有办法(使用模板等)在编译时检索字典数据而不是使用现有的字典结构?

Mat*_* M. 5

Clang和LLVM通过使用代码生成和预处理器技巧的组合生成包含其对象的表来解决您的问题.

您可以跳过任一步骤,具体取决于您自己的设置.例如:

// records.inc
EXPAND_RECORD(Foo, "Foo", 4);
EXPAND_RECORD(Bar, "Bar", 18);
EXPAND_RECORD(Bar2, "Bar", 19);
Run Code Online (Sandbox Code Playgroud)

现在,您可以生成枚举:

// records.h
enum Record {

#define EXPAND_RECORD(Name, String, Value) Name,
#include "records.inc"
#undef EXPAND_RECORD

};

char const* getRecordName(Record r);
int getRecordValue(Record r);

// records.cpp

char const* getRecordName(Record r) {
  switch(r) {
#define EXPAND_RECORD(Name, String, Value) case Name: return String;
#include "records.inc"
#undef EXPAND_RECORD
  }

  abort(); // unreachable, or you can return a "null" value
}

int getRecordValue(Record r) {
  switch(r) {
#define EXPAND_RECORD(Name, String, Value) case Name: return Value;
#include "records.inc"
#undef EXPAND_RECORD
  }

  abort(); // unreachable, or you can return a "null" value
}
Run Code Online (Sandbox Code Playgroud)

在Clang和LLVM中,代码生成阶段用于从更令人愉快的定义文件生成.inc.

它工作得很好......但请注意,枚举的任何修改都意味着完全重新编译.您可能希望采用"代码集"方法,其中枚举在内部使用但从不泄露到外部,稳定值(枚举的值)提供给客户端(unsigned),以便旧客户端可以链接到新库没有重新编译:它们将被限制使用旧的代码集,如果它稳定则没有问题.