【发布时间】:2020-09-26 07:53:20
【问题描述】:
我有一个看起来像这样的小错误函数:
template<typename ErrorType>
void throwError(const std::string &file,
const std::string &function,
unsigned int line,
const std::string &msg = "") {
std::ostringstream errMsg;
errMsg << file << ":" << line << ":" << function << ":"
<< "\nError: " << msg << std::endl;
std::cerr << errMsg.str();
throw ErrorType(errMsg.str());
}
然后我有一些使用该函数的宏:
#define INVALID_ARGUMENT_ERROR(msg) throwError<std::invalid_argument>(__FILE__, __func__, __LINE__, msg)
#define LOGIC_ERROR(msg) throwError<std::logic_error>(__FILE__, __func__, __LINE__, msg)
所以我可以这样做:
if (condition == bad)
LOGIC_ERROR("you did a bad");
但是当我想在错误消息中添加其他信息时,这很不方便,例如数字的值。
修改此函数以使我能够使用流而不是字符串的好方法是什么?所以我希望能够做到:
if (condition == bad)
LOGIC_ERROR("you did a bad because condition \"" << condition << " != " << bad);
我尝试将std::string string msg 更改为std::ostringstream,但不起作用。
【问题讨论】:
-
您可以使用
std::to_string()将条件转为字符串,并使用+运算符将分片的字符串拼接成一个字符串。
标签: c++ exception error-handling macros