How to print an element of a string vector which was inserted using a variable of type "std::any"

Viewed 56

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)
1 Answers

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;
Related