不带#define捕获__LINE__和__FILE__ [英] Capture __LINE__ and __FILE__ without #define
问题描述
尝试为以下C样式代码确定现代实现:
Trying to determine a "modern" implementation for the following C-style code:
#define logError(...) log(__FILE__, __LINE__, __VA_ARGS__)
可以使用可变参数模板或类似方法捕获此信息那不依赖 #define
吗?
Is is possible to capture this using variadic templates or something similar that does not rely on a #define
?
所需的用例:
logError( "Oh no! An error occurred!" );
其中 __ FILE __
和 __ LINE __
在后台捕获,但是反映了调用 logError
的文件名和行号。
Where __FILE__
, and __LINE__
are captured under the hood, but reflect the file name and line number of where logError
was called from.
推荐答案
实际上,当您要使用行号和文件名时,预处理器是唯一的选择。
Actually the preprocessor is the only choice when you want to work with line numbers and filenames.
对于编译器,无法使用行号和文件名作为函数调用的参数(或将它们存储在变量中)。
For the compiler it's not possible to use line numbers and filenames as arguments for function calls (or storing them in a variable).
在我的公司中,日志记录存在完全相同的问题。最后,我们用一个外部脚本扫描源文件,然后构建适当的函数来调用。
In my company we had the exactly same issue with logging. We ended up with an external script scanning the source files and then building proper functions to call.
这篇关于不带#define捕获__LINE__和__FILE__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!