C++:如何使用id,string和named constant创建一个数组?

-1 c++ symbols constants lookup-tables c++11

我经常在我的代码中使用const查找表,它由id和字符串组成.但为了便于阅读,最好使用符号名称(命名常量)而不是id.例:

class LookupTable
{
   map<int,string> m { {10,"red"}, {20,"blue"}, {30,"green"} };
   enum { col_rd = 10, col_bl = 20, col_gr = 30 };
};

LookupTable tab;
cout << tab.m[10];      // "red", using the id
cout << tab.m[col_bl]   // "blue", using a symbol

cout << tab.m[11];      // Typo! Compiler does not check this
cout << tab.m[col_xy];  // Typo! Compiler will complain
Run Code Online (Sandbox Code Playgroud)

在编译时也将检查使用符号名称的拼写错误.

但我喜欢在一个地方定义元素的符号名称,id和字符串,而不是在上部定义值,然后在类声明的下半部分定义命名常量,特别是如果表是相当长.例如,我想写一些像:

mytable.init = { { col_rd, 10, "red" },    // define the symbol names and 
                 { col_bl, 20, "blue" },   // values at one place
                 { col_gr, 30, "green" } };
Run Code Online (Sandbox Code Playgroud)

这可以通过模板还是与#define宏结合使用?

Und*_*nda 5

身份对我来说似乎毫无用处.你能不能做到以下几点?

struct LookupTable
{
    enum ColorType
    {
        col_rd,
        col_bl,
        col_gr
    }

    std::map<ColorType, std::string> m;
};
Run Code Online (Sandbox Code Playgroud)

然后,你可以这样做:

LookupTable table;

table.m = {{LookupTable::col_rd, "red"},
           {LookupTable::col_bl, "blue"},
           {LookupTable::col_rd, "green"}};
Run Code Online (Sandbox Code Playgroud)