c++ - 如何打印使用 "std::any"类型的变量插入的字符串 vector 的元素

标签 c++ c++17 stdany

这是我的 C++ 代码的主要功能。

int main() {
vector<string> a;
any x;
x="Hello";
a.insert(a.begin(),any_cast<string>(x));
cout<<a[0]<<endl;
}

这给了我一个像这样的错误:

terminate called after throwing an instance of 'std::bad_any_cast'
  what():  bad any_cast
Aborted (core dumped)

最佳答案

问题是,"Hello" 的类型为 const char[6] 并且会衰减为 const char*,它不是 std::string。这就是为什么当您尝试从 std::any 获取 std::string 时,会得到 std::bad_any_cast

您可以更改为获取const char*,例如

a.insert(a.begin(),any_cast<const char*>(x));

或者从头开始将 std::string 分配给 std::any

x=std::string("Hello");

或者使用literals (自 C++14 起)

x="Hello"s;

关于c++ - 如何打印使用 "std::any"类型的变量插入的字符串 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62570666/

相关文章:

c++ - 使用 std::apply 遍历元组元素

c++ - 什么比 std::pow 更快?

c++ - (C++)乘法不会产生预期的结果

c++ - 结合 static_cast 和 std::any_cast

c++ - 如何返回带有捕获的 unique_ptr 的 lambda

c++ - 在没有 RTTI 的情况下检查 std::any 的类型

c++ - 我们如何将 int* 的地址传递给使用 void ** 作为参数的函数?

c++ - 可以比较 std::type_info 上的指针是否在常量表达式中相等?

c++ - 为什么 std::any 没有 unsafe_any_cast?

c++ - 是否可以从std::any使用std::reference_wrapper创建std::any?