0

Is there a way to create a data type that can holds both integers and strings in C++?

For example, create a data type with name sti that I can define both integers and strings variables with it:

sti a = 10; //this is integer
sti b = "Hello"; //and this is string
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 12
    `std::variant`??? – fabian Aug 14 '22 at 17:21
  • 2
    Yes, but there's not enough information here to describe what to do. Does it need to hold **both** an integer and a string at the same time, or just one or the other? If it's the latter, does that stay the same, or would you need to change from one to the other later on? – Pete Becker Aug 14 '22 at 17:24
  • @PeteBecker Yes, it's the latter, and does stay the same. – Just a homo sapiens Aug 14 '22 at 17:28
  • Duplicate: [How to use a single variable which can have multiple data types in C++](https://stackoverflow.com/questions/62079146/how-to-use-a-single-variable-which-can-have-multiple-data-types-in-c) – Jason Aug 27 '22 at 16:50

2 Answers2

7

You can use std::variant to achieve this which is C++17 feature. Refer this link to know more.

Following is code sample. See it working here:

#include <iostream>
#include <variant>
#include <string>

int main()
{
    using sti = std::variant<int, std::string>;
    sti a = 10;
    sti b = "Hello";
    std::cout<<std::get<int>(a) << " | " <<
                std::get<0>(a) <<std::endl; // Same as above
    
    std::cout<<std::get<std::string>(b) << " | " <<
                std::get<1>(b) <<std::endl;// Same as above
    return 0;
}
cse
  • 4,066
  • 2
  • 20
  • 37
1

You could use something like this:

struct Sti
{
    int m_number;
    std::string m_number_as_string;

    Sti(int number)
    {
        m_number = number;
        m_number_as_string = std::to_string(number);
    }
    Sti(const std::string& s)
    {
        m_number_as_string = s;
        m_number = std::stoi(s);
    }
};

The above example is one of many possible implementations.
The missing methods are an exercise for the OP or reader.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • How do I overload operator<< for this struct? – Just a homo sapiens Aug 21 '22 at 10:16
  • It's amazing what you can find by searching the internet for [overloading operator << for a struct](https://stackoverflow.com/questions/17693262/overload-operator-and-in-a-c-struct). FYI, searching the internet is usually much faster than posting to StackOverflow **and waiting for an answer**. – Thomas Matthews Aug 21 '22 at 17:36
  • See also: https://stackoverflow.com/questions/6815561/good-reference-for-c-iostreams and all books by Scott Meyers. – Thomas Matthews Aug 21 '22 at 17:38