+ 4
Is it possible to declare a C++ Variable that can contain an Intenger or a String?
Like a 2-in-one-container, See i'm searching for a method to do this, but I'm not gettin anywhere.
6 Answers
+ 13
Do a struct, which contains an int and a string. (?) Not sure if it is what you want.
struct myType
{
int integer;
string str;
};
int main()
{
myType var;
var.integer = 3939;
var.str = "Hello Planet";
//codes
}
---
Or you can just declare a string variable, and explicitly convert its contents to integer whenever needed.
+ 7
It's possible to achieve this using void pointers... But it's messy and difficult to implement
here's a code if you want to see how it looks:
https://code.sololearn.com/c29KMo1XirBX/?ref=app
+ 4
STL has you covered!!!
auto pair = std::make_pair<int, std::string>(22, "fslkaf");
+ 2
Thanks a lot for all the helpful comments👍👍
+ 1
If you want in the same space in memory, in a way that you can use one or another, there is a structure called union.
http://en.cppreference.com/w/cpp/language/union
- 1
hey its me again, no i think its impossible and also googling it i dont find anything, if you tell me what do you want to do in particular i will be glad to help you