检查 std::any 变量是否包含 std::string 时出现问题
Problem when checking whether std::any variable holds a std::string
在 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”;
}
这可能会解决您的问题,谢谢
- 输入std::数组时出现问题
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- GCC 问题与 static_cast<std::u16string>
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 在 std::tuple 上使用 std::variant 的问题
- std::max() 函数与定点实现的比较中的问题
- 使用 CImg 库的 std::min 和 std::max 的编译问题
- 如何在 cpp 中使用 std::enable_if 从模板中处理此类问题
- 关于 std::bitset 构造函数的几个问题?
- 'std::filesystem::d irectory_iterator' 编译器问题
- C++ 中 std::vector 的内存问题
- 我有一个关于C++提升的问题:: asio 和 std :: 异步
- std::p 设置或多组的修订问题
- 没有'str'成员在 GCC 和 Clang 'std::basic_ostream<char>',但 MSVC 没有问题
- 我对 std::unique(算法)C++有问题
- 关于在成员重载中使用 std::move() 的问题
- 示例代码中使用分隔符将 std::string 拆分为 std::vector 的范围问题
- 安卓ndk发布套接字和std问题
- "using namespace std;"问题