Patrik Nusszer
Patrik Nusszer

Reputation: 480

Problem when checking whether std::any variable holds a std::string

In c++ you can compare two type_info objects.

There is the std::any class. It has a member .type() that will also return a type_info object telling you the type it contains. I can use typeid(THE_TYPE) and compare the two.

The following code works:

std::any x = 6;

if (x.type() == typeid(int)) {
    cout << "x is int";
}

But the following will not work:

std::any x = "string literal";

if (x.type() == typeid(std::string)) {
    cout << "x is string";
}

What am I doing wrong? How do I check if a variable is a string?

Upvotes: 2

Views: 996

Answers (3)

songyuanyao
songyuanyao

Reputation: 172934

The problem is, "string literal" is not of type std::string, it's a c-style string, i.e. a const char[15] itself. And std::any takes it as const char*. So if you change the condition as follows you'll get "x is string" printed out.

if (x.type() == typeid(const char*))

To solve the issue you can pass an std::string to std::any explicitly.

std::any x = std::string("string literal");

Or use literal.

using namespace std::string_literals;
std::any x = "string literal"s;

Upvotes: 11

Rajkumar Ananthu
Rajkumar Ananthu

Reputation: 404

Basically, the statement std::any x = “string literal”; treats "string literal" as a character constant. So the type of x would be const char*. To make the code work as you want, you can change that as :

std::any x = std::string(“string literal”);

if (x.type() == typeid(std::string)) {
 cout << “x is string”;
}

This may solve your problem, Thanks

Upvotes: 0

JVApen
JVApen

Reputation: 11317

std::any x = “string literal”; does not store a std:: string. It stores a char const [15].

I think the right way of fixing it, is by ensuring you store std::string. Either by writing: std::any x = std::string{ “string literal”}; or by writing std::any x = “string literal”s; (this last one needs a using for the literals using namespace std::string_literals;)

Personally, I would also consider std::string_view to put in the any, as it doesn't allocate memory for the string. However it might complicate the usage.

Upvotes: 1

Related Questions