![](/img/trans.png)
[英]In a multithreaded c++ program using boost, is there any way to get a pointer to the current thread?
[英]C++ - is there any way to get the current executing line
我需要创建一个异常处理,因为我还要求打印操作的状态,例如
“文件打开:操作成功完成”
“文件关闭:操作成功完成”,
等等
是否有诸如__LINE__,__FUNCTION__,__FILE__
这样的宏?
还是有任何增强功能可以做到这一点?
__LINE__
和__FILE__
在C ++中都可用,就像在C中一样。唯一的警告是它们是在编译时扩展的宏,因此,如果将它们放在宏或模板中,它们可能会或可能不会发挥您的期望。
我认为答案是,您想对要评估的表达式进行字符串化处理吗?
码:
#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';
}
}
我不确定您到底要问什么,但这是我自己的库中的代码示例:
/**
* \brief Convenient alias to create an exception.
*/
#define EXCEPTION(type,msg) type((msg), __FUNCTION__, __FILE__, __LINE__)
基本上,这使我可以编写:
throw EXCEPTION(InvalidParameterException, "The foo parameter is not valid");
当然,这里的InvalidParameterException
是我设计的类,它使用额外的参数来保存函数,文件和创建异常的行。
它具有以下构造函数:
InvalidParameterException::InvalidParameterException(
const std::string& message,
const std::string& function,
const std::string& file,
int line);
当然,如果您不想抛出异常,而只是将输出输出到日志文件中,则显然可以使用相同的“技巧”。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.