+ 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.

28th Jul 2017, 7:32 PM
BwD//Felix Janetzki
BwD//Felix Janetzki - avatar
6 Réponses
+ 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.
28th Jul 2017, 9:27 PM
Hatsy Rei
Hatsy Rei - avatar
+ 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
28th Jul 2017, 8:28 PM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 4
STL has you covered!!! auto pair = std::make_pair<int, std::string>(22, "fslkaf");
28th Jul 2017, 10:28 PM
aklex
aklex - avatar
+ 2
Thanks a lot for all the helpful comments👍👍
28th Jul 2017, 10:32 PM
BwD//Felix Janetzki
BwD//Felix Janetzki - avatar
+ 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
29th Jul 2017, 12:23 PM
Denis Felipe
Denis Felipe - avatar
- 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
28th Jul 2017, 7:59 PM
Matte
Matte - avatar