non*_*ot1 13 c++ string static readonly string-table
在C++中创建全局和静态字符串表的正确方法是什么?
通过"全局",我的意思是:可以从任何包含标题的文件中使用.但不是某些运行时创建的singelton objcet的一部分.
通过"静态",我的意思是:由于很少的运行时间设置可能.只读存储器页面中的数据.每个应用只有1个数据实例.
通过"字符串",我的意思是:Null终止的字符数组很好.std :: string会很好,但我不认为它可以用上面的方法来完成.正确?
通过"表",我的意思是:我的意思是一个可索引的数组.所以我猜本身不是一张桌子.但是我在这一点上很灵活.开放的想法.
通过"C++",我的意思是:C++而不是C.(更新:C++ 98,而不是C++ 11)
Jon*_*art 10
strings.h
extern const char* table[];
Run Code Online (Sandbox Code Playgroud)
strings.cpp
const char* table[] = {
"Stack",
"Overflow",
}
Run Code Online (Sandbox Code Playgroud)
另一种观点,使用查找表的错误代码:
err.h
#define ERR_NOT_FOUND 0x1004
#define ERR_INVALID 0x1005
bool get_err_msg(int code, const char* &msg);
Run Code Online (Sandbox Code Playgroud)
err.cpp
typedef struct {
int errcode;
const char* msg;
} errmsg_t;
static errmsg_t errmsg_table[] = {
{ERR_NOT_FOUND, "Not found"},
{ERR_INVALID, "Invalid"}
};
#define ERRMSG_TABLE_LEN sizeof(errmsg_table)/sizeof(errmsg_table[0])
bool get_err_msg(int code, const char* &msg){
msg = NULL;
for (int i=0; i<ERRMSG_TABLE_LEN; i++) {
if (errmsg_table[i].errcode == code) {
msg = errmsg_table[i].msg;
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include <stdio.h>
#include "err.h"
int main(int argc, char** argv) {
const char* msg;
int code = ERR_INVALID;
if (get_err_msg(code, msg)) {
printf("%d: %s\n", code, msg);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我确信有更多的C++方法可以做到这一点,但我真的是一名C程序员.
使用std::array
字符串文字.它没有构造函数,因此它将.rodata
像C数组一样静态加载,但它有一个标准的C++库接口.(迭代器,大小等)
啊:
#include <array>
extern std::array<const char*, 3> A;
Run Code Online (Sandbox Code Playgroud)
A.cpp:
std::array<const char*, 3> A = { "foo", "bar", "baz" };
Run Code Online (Sandbox Code Playgroud)
http://en.cppreference.com/w/cpp/container/array