如何创建一个带有id、字符串和命名常量的数组
C++: How to create an array with id,string and named constant?
我经常在代码中使用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
相关文章:
- 将错误作为从字符串常量到"char*"的已弃用转换 [-Wwrite-strings]
- 3 与错误最接近的总和:字符串常量之前的预期非限定 id
- 为什么字符串(常量字符* s,size_t pos,size_t len = npos)有效?
- 指向字符串常量的指针
- 警告:ISO C++禁止将字符串常量转换为'char*' [-Wwrite-strings]
- 为什么在波纹管程序中发生了从字符串常量到'char*'的警告已弃用的转换
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- 如何从字符串常量创建字符数组
- 将字符串常量转换为char
- C++ 字符串常量和静态初始化顺序惨败
- 使用 std::string 返回开关大小写块中的字符串常量
- 消除从字符串常量到'char*'的已弃用转换的最佳方法"
- 警告:ISO C++禁止将静态“constexpr char*”数据成员的字符串常量转换为“char*”
- 字符常量或字符串常量
- Swig:如何类型映射c ++字符串常量和python字符串?
- 字符串常量之前的预期构造函数、析构函数或类型转换
- 为什么从字符串常量到"char*"的转换在 C 中有效,但在C++中无效
- 警告:已弃用从字符串常量到 'char* 的转换
- 无法获得通过C++警告:(和崩溃后)已弃用从字符串常量到"char*"的转换 [-Wwrite-strings]
- 错误:字符串常量 extern "a" { 之前应为非限定 ID