繁体   English   中英

如何修改C ++ runtime_error的字符串?

[英]How can I modify the what string of a C++ runtime_error?

我有一个继承自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)
}
static std::string get_message(unsigned int id) {
    std::stringstream ss;
    ss << "invalid type ID " << id;
    return ss.str();
}
SomeEx(unsigned int id) 
    : runtime_error(get_message(id)) 
{}

无关:我们使用字符串.what()的原因是使人们停止使用错误号。

当然: SomeEx(unsigned int id) : runtime_error(std::to_string(id)) { }

如今,您可以使用lambda并直接调用它来添加到Mooing Duck的答案中:

SomeEx(unsigned int id) :
    std::runtime_error {
        [](const auto id) {
            std::ostringstream ss;

            ss << "invalid type ID " << id;
            return ss.str();
        }(id)
    }
{
}

如果您可以将数字转换为字符串,则只需将它们附加:

#include <string>
#include <stdexcept>

std::string BuildMessage(std::string const&  msg, int x)
{
    std::string result(msg);

    // Build your string here
    return result;
}

class SomeEx : public std::runtime_error
{
    public:
        SomeEx(const std::string& msg)
            : runtime_error(BuildMessage(msg, id)) { }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM