如何创建一个带有id、字符串和命名常量的数组

C++: How to create an array with id,string and named constant?

本文关键字:字符串 常量 id 数组 创建 何创建 一个      更新时间:2023-10-16

我经常在代码中使用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

使用符号名也会在编译时检查是否有拼写错误。

但是我喜欢在一个地方为元素定义符号名、id和字符串,而不是在上面部分定义值,然后在类声明的下面部分定义命名常量,特别是当表很长时。例如,我想这样写:

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

是否可以通过模板或与#define宏结合来实现?

id对我来说似乎没用。你不能做以下的吗?

struct LookupTable
{
    enum ColorType
    {
        col_rd,
        col_bl,
        col_gr
    }
    std::map<ColorType, std::string> m;
};

然后,你可以这样做:

LookupTable table;
table.m = {{LookupTable::col_rd, "red"},
           {LookupTable::col_bl, "blue"},
           {LookupTable::col_rd, "green"}};

我曾经在Varnish缓存中看到过这种技术,它使用宏-但是您说您对此没有问题:)

In color_tags.hpp:

// Define the color tags
COLOR_TAG(col_rd, 10, "red")
COLOR_TAG(col_bl, 20, "blue")
COLOR_TAG(col_gr, 30, "green")

main.cpp中的使用:

#include <map>
#include <string>
#include <iostream>
/// Enumeration of different color codes, we use a bit of
/// macro uglyness to makes this easy
enum class color_type
{
    #define COLOR_TAG(id,value, msg) id = value,
    #include "color_tags.hpp"
    #undef COLOR_TAG
    terminate_tag
};
int main()
{
    std::map<color_type, std::string> m =
    {
        #define COLOR_TAG(id, value, msg) {color_type::id, msg},
        #include "color_tags.hpp"
        #undef COLOR_TAG
        {color_type::terminate_tag, "undefined"}
    };
    std::cout << m[color_type::col_rd] << std::endl;
    std::cout << m[color_type::col_bl] << std::endl;
    std::cout << m[color_type::col_gr] << std::endl;
    return 0;
}
输出:

$ g++ main.cpp -std=c++11
$ ./a.out 
red
blue
green