首页 > 解决方案 > 如何打印使用“std::any”类型的变量插入的字符串向量的元素

问题描述

这是我的 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)

标签: c++c++17stdany

解决方案


问题是,"Hello"是类型const char[6]并且会衰减到const char*,它不是std::string。这就是为什么您std::bad_any_cast在尝试std::stringstd::any.

你可以改变得到const char*喜欢

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

std::string或从头开始分配std::any

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

或使用文字(C++14 起)

x="Hello"s;

推荐阅读