问题描述
我可以使用 __ LINE __
作为方法参数,但我想要一个简单的方法在使用字符串的函数中使用它。
I can use __LINE__
as a method parameter just fine, but I would like an easy way to use it in a function that uses strings.
例如,我有这样的:
11 string myTest()
12 {
13 if(!testCondition)
14 return logError("testcondition failed");
15 }
我希望函数的结果是:
我可以写logError吗?
How can I write logError? Does it have to be some monstrosity of a macro?
推荐答案
为什么你还需要一个字符串?整数有什么问题?这里有两种方法可以写 logError()
:
Why do you even need it as a string? What's wrong with an integer? Here are two ways you could write logError()
:
#define logError(str) fprintf(stderr, "%s line %d: %s\n", __FILE__, __LINE__, str)
// Or, forward to a more powerful function
#define logError(str) logError2(__FILE__, __LINE__, str)
void logError2(const char *file, int line, const char *str);
如果你真的需要一个字符串,你可以使用字符串化操作符#
,但是由于宏的工作方式,您需要将它包装在两个宏中:
If you really need the line as a string, you can use the stringizing operator #
, but because of the way macros work, you'll need to wrap it in two macros:
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)
现在 LINE_STRING
是一个宏,将扩展为包含当前行号的字符串,如果你只有一个级别的宏(即如果你有 #define STRINGIZE(x)#x
),那么你会得到字符串 __LINE __
每次展开它,这不是你想要的。
And now LINE_STRING
is a macro that will expand to a string containing the current line number wherever it is expanded. If you only had one level of macros (i.e. if you had #define STRINGIZE(x) #x
), then you would get the literal string "__LINE__"
every time you expanded it, which is not what you want.
这篇关于如何在字符串中使用编译时常数__LINE__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!