From: Ben Hutchings 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: 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" 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 template T f(); template <> int f() { return 1; } template <> long f() { return 2L; } int main() { int x = f(); long y = f(); 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 and f 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.