Re: The c++ way?

From: JKop (NULL_at_NULL.NULL)
Date: 06/03/04


Date: Thu, 03 Jun 2004 20:07:54 GMT

JustSomeGuy posted:

> JKop wrote:
>
>> JustSomeGuy posted:
>>
>> > By the way is there such a thing as a Variant in C++ as there is in
>> > Visual Basic?
>>
>> Here is how the Variant type in VB works:
>>
>> class Variant
>> {
>> private:
>>
>> enum
>> {
>> intE,
>> charE,
>> doubleE
>> } current_type;
>>
>> union
>> {
>> int intD;
>> char charD;
>> double doubleD;
>> } data;
>>
>> public:
>> //Assignment operator goes here, as well as other operators
>> };
>>
>> As you can see, Variant's are slow, and waste more memory. It's a
>> lose-lose situation, but then again if you're one of those "Visual
>> Basic, Dumb it Down" people, you may take a shine to it!
>>
>> -JKop
>
> Of course!
> A question though....
>
> In the public section I guess I can't add these...
>
> int Get(void);
> char Get(void);
> double Get(void);
>
> because the return type is not considered to be part of the
> signature... I guess however that I could do...
>
> void Get(int &x)
> void Get(char &x)
> void Get(double &x)
>
>
> But i think you are talking about operator= is that right?

In the above, you are using an actual member function to get the data.
Consider the following function:

void TakeNumber(int in_number);

Here's how *your* idea would work:

int main(void)
{
            Variant j;

            // ...

            TakeNumber( j.GetInt() );

            //or something like that

}

What I had in mind was actually declaring a "cast operator", so that you
could simply do the following:

int main(void)
{
            Variant j;

            // ...

            TakeNumber(j);

            TakeCharachter(j);

            TakeDouble(j);
}

The cast operator would be defined as so:

Variant::operator int(void)
{
            if (current_type == intE)
            {
                        return data.intD;
            }
            else
            {
                        throw "poo!";
            }
}

Variant::operator double(void)
{
            if (current_type == doubleE)
            {
                        return data.doubleD;
            }
            else
            {
                        throw "poo!";
            }
}

Or something along those lines!

-JKop