2

Here is my c++ Code's main function.

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

and this is giving me an error like this:

terminate called after throwing an instance of 'std::bad_any_cast'
  what():  bad any_cast
Aborted (core dumped)
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Avi H
  • 21
  • 1

1 Answers1

3

The problem is, "Hello" is of type const char[6] and would decay to const char*, it's not std::string. That's why you got std::bad_any_cast when trying to get std::string from the std::any.

You can change to get const char* like

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

Or assign std::string to the std::any from the beginning.

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

Or use literals (since C++14)

x="Hello"s;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405