I was reading through some questions on the differences between templates in some different programming languages. I understand that thanks mostly to this questions: What are the differences between Generics in C# and Java... and Templates in C++?. I did however get a little bit confused towards the end of the accepted answer when he starting talking about interfaces and when adding something. I understand the generals of interfaces mostly from this question: Explaining Interfaces to Students. I was still confused by what was stated in the question. So can someone better explain this last portion:
Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things:
In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example:
string addNames( T first, T second ) { return first.Name() + second.Name(); }
That code won't compile in C# or Java, because it doesn't know that the type T actually provides a method called Name(). You have to tell it - in C# like this:
interface IHasName{ string Name(); }; string addNames( T first, T second ) where T : IHasName { .... }
And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different (), but it suffers from the same problems.
The 'classic' case for this problem is trying to write a function which does this
string addNames( T first, T second ) { return first + second; }
You can't actually write this code because there are no ways to declare an interface with the + method in it. You fail.
C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple.
I really want to understand the code in this answer as I was very confused how the .Name() method would work in the IHasName interface. Is someone has a better example that can further explain how interfaces can be used to add something like a name to a Person class or something else...
EDIT: I am more interested in the Java code.