[英]C++ - is there any way to get the current executing line
I need to create an exception handling, in that I also asked to print the status of the operation like 我需要创建一个异常处理,因为我还要求打印操作的状态,例如
"file open : The operation completed successfully" “文件打开:操作成功完成”
"file close: The operation completed successfully", “文件关闭:操作成功完成”,
etc. 等等
Is there any macro for this like __LINE__,__FUNCTION__,__FILE__
? 是否有诸如
__LINE__,__FUNCTION__,__FILE__
这样的宏?
Or is there any boost function available to do this? 还是有任何增强功能可以做到这一点?
__LINE__
和__FILE__
在C ++中都可用,就像在C中一样。唯一的警告是它们是在编译时扩展的宏,因此,如果将它们放在宏或模板中,它们可能会或可能不会发挥您的期望。
I think the answer is that you want to stringify the expression you are evaluating? 我认为答案是,您想对要评估的表达式进行字符串化处理吗?
Code: 码:
#include <stdexcept>
#include <sstream>
#include <iostream>
void check_result(bool result, const char* file, int line_number, const char* line_contents)
{
if (!result) {
//for example:
std::stringstream ss;
ss << "Failed: " << line_contents << " in " << file << ' ' << line_number;
throw std::runtime_error(ss.str());
}
}
#define CALL_AND_CHECK(expression) check_result((expression), __FILE__, __LINE__, #expression)
bool foobar(bool b) { return b; }
int main()
{
try {
CALL_AND_CHECK(foobar(true));
CALL_AND_CHECK(foobar(false));
} catch (const std::exception& e) {
std::cout << e.what() << '\n';
}
}
I'm not sure what exactly you're asking but here is a code sample from my own library: 我不确定您到底要问什么,但这是我自己的库中的代码示例:
/**
* \brief Convenient alias to create an exception.
*/
#define EXCEPTION(type,msg) type((msg), __FUNCTION__, __FILE__, __LINE__)
Basically, this allows me to write: 基本上,这使我可以编写:
throw EXCEPTION(InvalidParameterException, "The foo parameter is not valid");
Of course here, InvalidParameterException
is a class I designed that takes extra parameters to hold the function, the file and the line where the exception was created. 当然,这里的
InvalidParameterException
是我设计的类,它使用额外的参数来保存函数,文件和创建异常的行。
It has the following constructor: 它具有以下构造函数:
InvalidParameterException::InvalidParameterException(
const std::string& message,
const std::string& function,
const std::string& file,
int line);
Of course, if you don't want to throw an exception but just output something to, say a logfile, you can obviously use the same "trick". 当然,如果您不想抛出异常,而只是将输出输出到日志文件中,则显然可以使用相同的“技巧”。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.