Thread: Overloading a variable with multiple data types

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    67

    Question Overloading a variable with multiple data types

    Hello everyone.

    I just had a simple question involving variables.
    I know how to declare integers using "int" and strings using "std::string".
    There exist other data types such as "char", "long", etc.

    I was wondering how I could assign multiple data types to one variable.

    Here is an example of how this overloaded variable would help:

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        multiple datatype variable "V" would be declared here
        cout << "Type in an integer or string: ";
        cin >> V;
        cout << endl;
        cout << "The number or letter you just typed was: ";
        cout << V;
    }
    This is a simple program that would let the user know the integer or string they typed in.

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The short answer would be that you can't. Various solutions exist, but this is hardly a good place for such a solution.
    In your example, the data you read is a string. A string can represent an integer, as well, so whatever the user typed it, you can print right back out. No problems.

    Is there anything else you need this multi-type variable for?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by CPlus View Post
    I was wondering how I could assign multiple data types to one variable.
    That's basically what the union keyword does:
    Other Data Types

    Although you might be thinking of something more like the Boost Any class:
    Chapter..2...Boost.Any
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Don't go polluting these newbies' minds, now!
    C++ is a type strict language. We should learn to play by the rules, not circumvent them!
    Union is a C relic, too. Dangerous thing.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Don't go polluting these newbies' minds, now!
    Indeed. I'd really like to see what cin >> x would do where x is an union / any.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Class types with a non-trival constructor, assignment operator, or destructor (such as std::string) also cannot be members of a union.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    While not necessarily in this case unions are still important data constructs and I think by ignoring them you are doing the OP a disservice. Same thing with advising against a variant (your Boost.any). Variants are extremely useful in database and other situations and though it may not be right for what the OP wants (it all depends on how you need to use it) trying to act as though they don't exist does no one any favors....
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by jeffcobb View Post
    While not necessarily in this case unions are still important data constructs and I think by ignoring them you are doing the OP a disservice. Same thing with advising against a variant (your Boost.any). Variants are extremely useful in database and other situations and though it may not be right for what the OP wants (it all depends on how you need to use it) trying to act as though they don't exist does no one any favors....
    While I don't dispute the importance of unions or variants, I disagree with you here.

    The number of applications that actually benefit from such constructs is very rare.

    It is even more of a disservice to encourage reliance on advanced or highly specialised techniques. It is a fact of life that inexperienced people often attempt to do things in a manner that is facilitated by advanced/advanced techniques, rather than thinking through their problem and coming up with relatively simple solution.

    The best way to decide if a poster is served by being pointed to advanced techniques or specialised libraries is to examine the logic of their question - how much thought has gone into the "solution" they have decided they need? In this case, all that's happened is a statement of a particular want, with little justification of why it is even needed.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    I would posit that the instances where variants are of use are not as rare as you would believe. Middleware for instance is a growing segment of the development world and is highly-reliant on them. But that isn't the point here: Limiting the development options for someone, even someone who is learning or even especially someone who is learning feels wrong. I believe in presenting options and letting the developer choose which is most appropriate. If they make a mistake, experience is a great teacher. I looked again at the OP question and to me it seems like they are asking if such a thing is possible, not if it is wise...
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The replies thus far have indicated that it is indeed possible.
    I also indicated that it was possible in my first reply.
    However, I stand by grumpy that in this situation, such a thing would likely be a bad thing.

    You must consider the factor that they are not professionals or experts. They are novices. Newbies. And as such, they usually don't understand what is wrong or bad. They just use it without truly understanding it.
    Teach a student gets and they will use it, even though it's bad. They will probably never realize how bad it is.
    I believe in properly teaching students the ways of being a programmer by guiding them through situations instead of throwing a lot of tools at them. They will never learn properly how and where to apply them.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    Jeff I agree with you that we should let the developer choose what is appropriate, but I think the ability to make that decision only comes with experience. I think almost every rule can be broken, but I think it's important to learn the "rules" (they're really more like guidelines) and why they exist before bending/breaking them. As a new programmer, the OP should be taught good coding habits.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  12. #12
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Well, if OP really wants to make his code work with a variant type, then it might look like this:

    Code:
    #include <boost/variant.hpp>
    #include <boost/lexical_cast.hpp>
    #include <string>
    #include <iostream>
    #include <ostream>
    #include <istream>
    
    typedef boost::variant<std::string, int> Variant;
    
    class output_variant: public boost::static_visitor<void>
    {
        std::ostream* p_os;
    public:
        output_variant(std::ostream& os): p_os(&os) {}
    
        template <class T>
        void operator()(const T& t) const
        {
            *p_os << t;
        }
    };
    
    std::ostream& operator<< (std::ostream& os, const Variant& var)
    {
        boost::apply_visitor(output_variant(os), var);
        return os;
    }
    
    std::istream& operator>> (std::istream& is, Variant& var)
    {
        std::string input;
        if (is >> input) {
            try {
                var = boost::lexical_cast<int>(input);
            }
            catch (const boost::bad_lexical_cast&) {
                var = input;
            }
        }
        return is;
    }
    
    using namespace std;
    int main()
    {
        //multiple datatype variable "V" would be declared here
        Variant V;
        cout << "Type in an integer or string: ";
        cin >> V;
        cout << endl;
        cout << "The number or letter you just typed was: ";
        cout << V;
    }
    Not sure if the effort is much worth it here, as you'd get the exact same result if you used a std::string instead of Variant...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  13. #13
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Hmmm. For those who don't want the OP to even know about things like unions and variants, I can understand your reason why but I still think my POV is valid enough too; if we treat beginners as only beginners and don't expose them to other things "for their own good" then that is all they will ever be (if we are the only source of information). It seems like there needs to be some kind of middle-ground as I can see where both sides are right, useful and correct while at the same time both are potentially damaging to their growth as a programmer.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  14. #14
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    Jeff, I don't think that anyone meant that the OP should never learn about unions and variants. I think the point was that since he's a beginner, he should learn the basics first to establish good coding habits before doing those things.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  15. #15
    Registered User
    Join Date
    Feb 2010
    Posts
    32
    I have to agree with NeonBlack here since i'm a beginner as well. Teach us the basics and how to get the code to do what we want with the easier stuff then gradually add more things to our database of knowledge, dumping all of it at once causes major mental meltdown

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Dynamic Array substitution in composite data variable
    By DavidDobson in forum C Programming
    Replies: 2
    Last Post: 08-12-2008, 04:29 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. data types help
    By Bud in forum C Programming
    Replies: 2
    Last Post: 06-27-2002, 12:35 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

Tags for this Thread