[Proposal]
Dave
Dave_member at pathlink.com
Sun Jun 18 12:02:25 PDT 2006
Sean Fritz wrote:
> In article <e7346j$1uo9$2 at digitaldaemon.com>, Walter Bright says...
>> Sean Fritz wrote:
>>>> T sqr(T) ( T x )
>>>> {
>>>> return x*x;
>>>> }
>>> Is the way Java Generics do it,
>> I didn't think Java supported function templates (only class templates).
>
> Yes, there are class and method level generics. There are none of the linking
> issues that come up from function templates (thank gods!).
>
> Class generics are (of course):
>
> class Foo<T> { ... }
>
> While method generics are:
>
> public void <T> T[] toArray(T[] arr) { ... }
>
So let's say we want to implement a generic sqr method in Java... How
would we do it? I came up w/ this after just a quick look at the spec.
to get the syntax right:
public class Test
{
public static void main(String args[])
{
Integer i = 100;
System.out.println(sqr(i));
int j = 1000;
System.out.println(sqr(j));
}
public static <T> T sqr(T x)
{
return x * x;
}
}
However, I get this when I compile:
Test.java:10: operator * cannot be applied to T,T
return x * x;
?
Thanks,
- Dave
> The distinction in placment of the type parameter is one of the weirdest
> syntactical choices in Java. It doesn't take long to master, but it constantly
> leaves you wondering why they did it.
>
> Also, they aren't really anything like templates except that they allow generic
> programming. It really takes several months to fully grok generics (especially
> with the Java Language Spec being the only decent reference at the moment).
>
> Sean
>
>
More information about the Digitalmars-d
mailing list