可以将#defines的列表转换为字符串 [英] Possible to convert list of #defines into strings
问题描述
假设我在外部库的头文件中有一个 #define
的列表。这些 #define
表示从函数返回的错误代码。我想写一个转换函数,它可以作为输入一个错误代码,并返回一个字符串文字表示实际的 #define
名称。
Suppose I have a list of #define
s in a header file for an external library. These #define
s represent error codes returned from functions. I want to write a conversion function that can take as an input an error code and return as an output a string literal representing the actual #define
name.
例如,如果我有
#define NO_ERROR 0
#define ONE_KIND_OF_ERROR 1
#define ANOTHER_KIND_OF_ERROR 2
我想要一个函数能够调用
I would like a function to be able to called like
int errorCode = doSomeLibraryFunction();
if (errorCode)
writeToLog(convertToString(errorCode));
并且拥有 convertToString()
自动转换该错误代码,而不是一个巨大的开关情况下看起来像
And have convertToString()
be able to auto-convert that error code without being a giant switch-case looking like
const char* convertToString(int errorCode)
{
switch (errorCode)
{
case NO_ERROR:
return "NO_ERROR";
case ONE_KIND_OF_ERROR:
return "ONE_KIND_OF_ERROR";
...
...
...
我有一个感觉,如果这是可能的,可能使用模板和元编程,但只有工作的错误代码实际上是一个类型,而不是一堆处理器宏。
I have a feeling that if this is possible, it would be possible using templates and metaprogramming, but that would only work the error codes were actually a type and not a bunch of processor macros.
推荐答案
我通常做巨大的开关case方式,虽然我使它有点更容易:
I normally do it the giant switch case way, although I make it somewhat easier with:
#define STR(code) case code: return #code
switch (errorCode)
{
STR(NO_ERROR);
STR(ONE_KIND_OF_ERROR);
}
这是一个很好的问题,有
This is a good question, I'm interested to see what better ways people have
这篇关于可以将#defines的列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!