如何修改 C++ 的 What 字符串运行时错误?
我有一个继承自 std::runtime_error
的类,如下所示:
#include <string>
#include <stdexcept>
class SomeEx : public std::runtime_error
{
public:
SomeEx(const std::string& msg) : runtime_error(msg) { }
};
所说的 msg
将始终类似于“无效类型 ID 43”。有没有办法用另一个构造函数(或另一个方法)构建“什么字符串”,以便我只提供整数类型 ID?像这样的东西:
SomeEx(unsigned int id) {
// set what string to ("invalid type ID " + id)
}
I have a class which inherits from std::runtime_error
like so:
#include <string>
#include <stdexcept>
class SomeEx : public std::runtime_error
{
public:
SomeEx(const std::string& msg) : runtime_error(msg) { }
};
Said msg
will always be something like "invalid type ID 43". Is there any way to build that "what string" with another constructor (or another method) so that I provide only the integer type ID? Something like:
SomeEx(unsigned int id) {
// set what string to ("invalid type ID " + id)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不相关:我们使用字符串
.what()
的原因是为了让人们停止使用错误数字。unrelated: the reason we have string
.what()
is so that people STOP USING ERROR NUMBERS.当然:
SomeEx(unsigned int id) : runtime_error(std::to_string(id)) { }
Sure:
SomeEx(unsigned int id) : runtime_error(std::to_string(id)) { }
如果您可以将数字转换为字符串,那么您可以简单地附加它们:
If you can convert the number into a string then you can simply append them:
添加到 Mooing Duck 的答案中,现在您可以使用 lambda 并直接这样调用它:
Adding to Mooing Duck's answer that nowadays you can use a lambda and directly call it as such: