Mail Archives: djgpp/2001/03/20/17:01:50
"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 -