This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
You can rid yourself of the warning by returning a Number and not a T. The warning is coming from this line:
return (T) sum;
You declare T as a subclass of Number, and *sum* is a variable of type Number. A superclass is not always able to be cast to a subclass. (i.e. String is a subclass of Object, but you can't just cast any Object to a String). This code compiles without warning:
because any subclass can be referred to by a superclass reference.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
The compiler is complaining because you are casting a Number to a T. This makes sense since you declared the function to return a T which needs to extend Number, but how do you know that sum is really the same run-time type as T and not some other class that extends Number? Well perhaps you do, but the compiler cannot tell since sum was declared as a Number.
I'm not too familiar with templates, but I think you can declare sum as a T instead. The other option, as Garrett pointed out, is to declare the function to return a Number instead of a T.