template vs polymorphism

it looks like they both do the same job, can you guys list all what they differ from each other?
Templates lead to generic code, while polymorphism can lead to dynamic code.
Polymorphism can be handled in implementation files, templates must be in header files (or "inline" but separated header files).

Polymorphism couldn't be used for some of the things templates can be used for. If I tried to implement an std::vector<T> using polymorphism with "vector" being the base, I'd need to make another class definition for every single type of vector that I wanted... plus it wouldn't even be good because surely the actual array pointer would need to be defined in the derived class, something which the base class knows nothing about. So you just end up have manual repeated code 100x times that does *almost* the same thing.

Template instantiation has to happen at compile time before the program is made, polymorphism can happen at runtime.

Templates also create hard-to-follow compile error, and can't do some of the things that polymorphism can, like change things dynamically (at run-time). Polymorphism allows nice arrays of base pointers to be made so that each element in a list can do a different dynamic behavior. Here's a simple but noteworthy example http://stackoverflow.com/a/9425976

PS I'm sure there's stuff I've missed or only just touched, and others that can probably explain the differences more in depth.
Last edited on
@Ganado
Im writing a Tile engine, but im not sure about making a template of tiles or polymorphic tiles

Topic archived. No new replies allowed.