提问人:funbotix 提问时间:9/2/2023 最后编辑:genpfaultfunbotix 更新时间:9/2/2023 访问量:47
带有 C 样式字符串 (const char*) 的 C x-macro 在使用时包含意外的引号
C x-macro with with C-style strings (const char*) include unexpected quotes when used
问:
我第一次尝试 x 宏似乎进展顺利,但我被下面的代码和输出所显示的一点难住了。基本上,没有按照我想要的方式工作的部分是创建指向 C 样式字符串的指针,其中指向的内容不包括引号字符。下面的代码在 Visual Studio 中编译时没有错误或警告,但输出包含不需要的引号字符。如果我不包含定义 x 宏的引号,我找不到任何方法来构建程序。谁能告诉我如何更改源,以便输出不包含这些不需要的引号字符(但包括所示的其他所有内容)?
#include <map>
#include <stdio.h>
#define rinfo \
X( REG1, 10 ) \
X( REG2, 20 ) \
X( REG3, 33 ) \
enum class RNAME {
#define X(NAME,VALUE) RNAME_ ## NAME = __COUNTER__,
rinfo
#undef X
};
const char* const rnames[] = {
#define X(NAME,VALUE) (const char* const) "\"" #NAME "\"",
rinfo
#undef X
};
std::map<std::string, RNAME> rmap = {
#define X(NAME,VALUE) { "\"" #NAME "\"", RNAME::RNAME_ ##NAME },
rinfo
#undef X
};
typedef struct {
RNAME regname;
const char* name;
uint32_t value;
}regx_t;
regx_t regs[] = {
#define X(NAME,VALUE) { RNAME::RNAME_ ## NAME, rnames[ (int)RNAME::RNAME_ ## NAME ], VALUE },
rinfo
#undef X
};
int main(int argc, char *argv[]){
int nErrors = 0;
int n = sizeof(rnames) / sizeof(const char*);
for (int i = 0; i < n; i++) {
std::map<std::string, RNAME>::iterator it;
it = rmap.find(rnames[i]);
if (it != rmap.end()) {
int index = (int)it->second;
printf("rname[%d] = %s = %u = %s\r\n", i,
rnames[i],
regs[index].value,
regs[index].name);
}
else {
++nErrors;
}
}
printf("RNAME::RNAME_REG1 = %d\n", RNAME::RNAME_REG1);
printf("RNAME::RNAME_REG2 = %d\n", RNAME::RNAME_REG2);
printf("RNAME::RNAME_REG3 = %d\n", RNAME::RNAME_REG3);
printf("%d errors found\n", nErrors);
return 0;
}
这是程序按原样创建的输出。
rname[0] = "REG1" = 10 = "REG1"
rname[1] = "REG2" = 20 = "REG2"
rname[2] = "REG3" = 33 = "REG3"
RNAME::RNAME_REG1 = 0
RNAME::RNAME_REG2 = 1
RNAME::RNAME_REG3 = 2
0 errors found
答: 暂无答案
评论