gpt4 book ai didi

c++ - 从模板化函数返回字符串时,bad_any_cast异常

转载 作者:行者123 更新时间:2023-12-02 10:17:43 27 4
gpt4 key购买 nike

我正在使用存储在unordered_map中的值创建配置文件解析器。配置值是字符串,整数,浮点数和 bool(boolean) 值的混合,因此我使用std::any将它们存储在无序映射中,如下所示:

static unordered_map<string, any> CONFIG_VALUES =
{
{"title", "The window title"},
{"xRes", 1024},
//...
};

我有一个通用的getter函数,允许检索配置值,如下所示:
template<typename T>
T GetValue(const string& valueName) const
{
auto result = CONFIG_VALUES.find(valueName);
if (result != CONFIG_VALUES.end())
{
return any_cast<T>(result->second);
}
else
{
throw std::runtime_error("Invalid config key");
}
}

我的代码可以编译,并且能够像这样成功地检索一个int:
int myXres = MyConfig->GetValue<int>("xRes");

但是,如果我尝试获取字符串:
string myTitle = MyConfig->GetValue<string>("title");

我崩溃了:
Unhandled exception at 0x00007FF99463A799 in program.exe: Microsoft C++ exception: std::bad_any_cast at memory location 0x000000DCD76FDCE8. occurred

在Visual Studio调试器本地语言中,我看到字符串的std::any类型是
type    0x00007ff6950f2328 {program.exe!char const * `RTTI Type Descriptor'} {_Data={_UndecoratedName=0x0000000000000000 <NULL> ...} }  

我怀疑“char const *”可能是这里的问题(因为我们将“string”作为模板参数传递),但是我不确定如何解决它……(或者,也许这是一个红色的问题)。鲱鱼)。

有任何想法吗?

最佳答案

您认为值是char const*是正确的。您需要将其存储为 map 中的std::string,如下所示:

static unordered_map<string, any> CONFIG_VALUES =
{
{"title", std::string("The window title")},
{"xRes", 1024},
//...
};

或者,您可以将 any_cast设置为正确的类型,如下所示:
string myTitle = GetValue<char const*>("title");

这是一个有效的 demo

关于c++ - 从模板化函数返回字符串时,bad_any_cast异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61391535/

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