gpt4 book ai didi

c++ - 异常消息 : Insert String Representation of Faulty Value

转载 作者:行者123 更新时间:2023-11-30 05:22:22 30 4
gpt4 key购买 nike

如果 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));

最佳答案

如前所述,不可能在所有情况下 100% 做到这一点。

您必须指定模板契约的一部分是无论作为参数传递的类都必须支持 operator std::string .

你也可以写,作为你的契约(Contract)的一部分,数字类型也将被允许,你将在你的模板中实现它,作为使用 std::to_string 的特化.

为了稳健的实现,在这种情况下我会使用 SFINAE试试std::to_string , operator std::string ,如果两者都失败,则在异常消息中使用一些乏味的标签,如“未知类型”。也许使用 typeid与我的编译器的 demangler 一起,至少从中得到一个 C++ 类型名称。

关于c++ - 异常消息 : Insert String Representation of Faulty Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39688046/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com