【问题标题】:Excpetion Message: Insert String Representation of Faulty Value异常消息:插入错误值的字符串表示
【发布时间】:2016-09-25 14:36:25
【问题描述】:

如果T 类型的key 不是有效键,我想抛出domain_error 类型的异常。 但我不知道如何将任何类型的T 转换为字符串,只要定义了T::operator std::string(),例如int 不支持这个。

这显然是错误的,因为它只适用于非常特定的类型:

throw std::domain_error("key error: "+static_cast<std::string>(key));

如何做到这一点?

编辑

建议使用模板规范后我的解决方案

template <class T> std::string to_string(const T t)
    {
        return static_cast<std::string>(t);
    }

    template <> std::string to_string<unsigned int>(const unsigned int i)
    {
        std::stringstream ss;
        std::string ret;
        ss << i;
        ss >> ret;
        return ret;
    }

...

std::string domain_error(const IS& is) const
    {
        using namespace IDTranslator_detail;
        return "key error: "+to_string(is), "error";
    }

...

throw std::domain_error(domain_error(key));

【问题讨论】:

    标签: c++ string exception casting


    【解决方案1】:

    如上所述,在所有情况下都无法做到 100%。

    您必须为您的模板指定合同的一部分,即作为参数传递的任何类都必须支持operator std::string

    作为合同的一部分,您还可以写下也允许使用数字类型,并且您将在模板中实现这一点,作为使用 std::to_string 的专业化。

    对于一个健壮的实现,在这种情况下,我会使用SFINAE 来尝试std::to_stringoperator std::string,如果两者都失败,请使用一些平淡的标签,例如异常消息中的“未知类型”。或许可以将typeid 与我的编译器的解码器一起使用,至少可以从中获得一个 C++ 类型名称。

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多