检查 std::any 变量是否包含 std::string 时出现问题

Problem when checking whether std::any variable holds a std::string

本文关键字:std 问题 string 是否 any 变量 检查 包含      更新时间:2023-10-16

在 c++ 中,您可以比较两个type_info对象。

std::any类。它有一个成员.type(),该成员还将返回一个type_info对象,告诉您它包含的类型。我可以使用typeid(THE_TYPE)并比较两者。

以下代码有效:

std::any x = 6;
if (x.type() == typeid(int)) {
cout << "x is int";
}

但以下方法不起作用:

std::any x = "string literal";
if (x.type() == typeid(std::string)) {
cout << "x is string";
}

我做错了什么?如何检查变量是否为字符串?

问题是,"string literal"不是std::string类型,它是一个 c 风格的字符串,即const char[15]本身。std::any认为这是const char*.因此,如果您按如下方式更改条件,您将获得"x is string"打印出来。

if (x.type() == typeid(const char*))

要解决此问题,您可以将std::string显式传递给std::any

std::any x = std::string("string literal");

或者使用文字。

using namespace std::string_literals;
std::any x = "string literal"s;

std::any x = “string literal”;不存储std:: string。它存储一个char const [15]

我认为修复它的正确方法是确保您存储 std::string。要么通过写作:std::any x = std::string{ “string literal”};要么通过写std::any x = “string literal”s;(最后一个需要用于文字using namespace std::string_literals;(

就个人而言,我也会考虑std::string_view放入 any,因为它不会为字符串分配内存。但是,这可能会使使用复杂化。

基本上,语句std::any x = “string literal”;将"字符串文字"视为字符常量。所以x的类型将是const char*. 要使代码按预期工作,您可以将其更改为:

std::any x = std::string(“string literal”);
if (x.type() == typeid(std::string)) {
cout << “x is string”;
}

这可能会解决您的问题,谢谢