gpt4 book ai didi

c++ - token 粘贴和 __LINE__

转载 作者:太空狗 更新时间:2023-10-29 19:39:35 25 4
gpt4 key购买 nike

我正在编写一个简单的宏来显示 TRACE 信息。

这是我用的,

#ifdef __DEBUG__
#define TRACE { PrintErrorMsg("Trace exception at " __FILE__ "LineNo:"##(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif

这适用于FILE,但似乎不适用于LINE,知道我该如何处理这个问题。我也已经尝试过字符串运算符。这是吼叫。

#ifdef __DEBUG__
#define TRACE { PrintErrorMsg("Trace exception at " __FILE__ "LineNo:"#(__LINE__) "Function: " __FUNCTION__ " " );}
#else
#define TRACE
#endif

没有参数和有双参数,例如 - __LINE__((__LINE__))知道我该如何处理这个问题吗?

我想出了这个,

#ifdef __DEBUG__
#define ERROR_MSG_BUF_SIZE 1024
#define TRACE { char * error_msg_buffer = new char[ERROR_MSG_BUF_SIZE]; \
sprintf(error_msg_buffer,"Trace Exception at file: %s ,Line : %d , Function %s \n",__FILE__,__LINE__,__FUNCTION__);\
PrintErrorMsg(error_msg_buffer );\
delete[] error_msg_buffer;}
#else
#define TRACE

但我想在不使用 sprintf 的情况下做到这一点,而只是通过字符串和标记粘贴。有什么想法吗?

#endif

--提前致谢--

最佳答案

当您尝试使用 #x 将某些内容字符串化时,x 必须是一个宏参数:

#define FOO #__LINE__ /* this is not okay */
#define BAR(x) #x /* this is okay */

但是你不能简单地说 BAR(__LINE__),因为这会将 token __LINE__ 传递给 BAR,它会立即变成一个没有扩展的字符串(这是设计使然),给出 "__LINE__"。 token 粘贴运算符 ## 也会发生同样的事情:它们的操作数的扩展永远不会发生。

解决方案是添加间接寻址。你应该总是在你的代码库中的某个地方有这些:

#define STRINGIZE(x) STRINGIZE_SIMPLE(x)
#define STRINGIZE_SIMPLE(x) #x

#define CONCAT(first, second) CONCAT_SIMPLE(first, second)
#define CONCAT_SIMPLE(first, second) first ## second

现在 STRINGIZE(__LINE__) 变成了 STRINGIZE_SIMPLE(__LINE__),它被完全扩展为(例如)#123,结果是“123”。呸!如果我想要原始行为,我会保留 STRINGIZE_SIMPLE。所以你的代码应该是这样的:

#include <iostream>

#define STRINGIZE(x) STRINGIZE_SIMPLE(x)
#define STRINGIZE_SIMPLE(x) #x

#define TRACE() \
PrintErrorMsg("Trace exception in " __FILE__ \
" at line number " STRINGIZE(__LINE__) \
" in function " __FUNCTION__ ".")

void PrintErrorMsg(const char* str)
{
std::cout << str << std::endl;
}

int main()
{
TRACE();
}

关于c++ - token 粘贴和 __LINE__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com