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

标签 c++ string templates exception any

我正在使用存储在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/

相关文章:

c++ - 在函数外吞下分号的宏

c++ - 识别字符串中的字符

django - Django:如何从模板调用 View 函数?

c++ - 如何检查静态成员变量模板?

php - 使用 Smarty 或 Backbone.js 制作 javascript 模板

c++ - 使用 OpenCV 在 C++ 中按元素最小化两个图像

c++ - 在 C++ 或 C++11 中重新抛出类型化异常

c++ - 如何将 C++ std::vector 传输到 openCL 内核?

python - 拆分包含字符串和整数的列表

python - 两个字符串之间最长匹配序列的正则表达式