delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/03/20/17:01:50

From: Ben Hutchings <ben DOT hutchings AT roundpoint DOT com>
Newsgroups: comp.lang.c++,comp.os.msdos.djgpp
Subject: Re: GENERAL DATA TYPE (Do you need one ?)
Date: 20 Mar 2001 13:50:21 -0800
Organization: Roundpoint Ltd
Lines: 61
Sender: bhutchings AT BENWORLD
Message-ID: <uk85k6rfm.fsf@roundpoint.com>
References: <9988r4$k33$1 AT tron DOT sci DOT fi>
NNTP-Posting-Host: 63.140.46.221
X-Trace: fu-berlin.de 985125072 176065 63.140.46.221 (16 [70929])
X-Newsreader: Gnus v5.6.45/XEmacs 21.1 - "Canyonlands"
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

"Traveler" <traveler AT netti DOT fi> writes:

> Hi to all !
> 
> I have only one (and maybe a stupid ?) question:
> Do you have a need for an general data type (something like the "Object" in
> Java) ?
> 
> Currently the only thing I see this could be used is in a function that has
> no parameters but still needs to return different kind of types (template is
> not a solution here...)

Templates are a solution if your compiler implements them correctly.

    #include <iostream>

    template <typename T> T f();
    template <> int f<int>() { return 1; }
    template <> long f<long>() { return 2L; }

    int main()
    {
        int x = f<int>();
        long y = f<long>();
        std::cout << x << ' ' << y << std::endl;
        return 0;
    }

Compiling this with g++ and then running it produces the output '1 2',
which is what I expected.

The other compiler I have to hand, VC++, incorrectly considers the
specialisations f<int> and f<long> to be overloads of the same
function, and since their signatures differ only by return type it
reports an error.

> Example:
> 
> Object    f(void);    // Function overloading is not possible if only the
> return value changes
>                             // int f(void), short f(void), etc... are not
> possible
> 
> // The following would be possible...
> int    x = f();
> long    y = f();
> // So would this...
> int    x = 10;
> int    y = 20;
> Object    tmp;
> tmp = x;
> x = y;
> y = tmp;    // Now, x has 20 & y has 10

It might be possible to do something like this in C++, but I don't see
how it's desirable.  C++ doesn't give you quite the same flexibility
in dynamic type conversion, but parameterised types and functions
allow you to avoid most of the cases where Java needs it (I think).

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019