+ 3
How is C++ function template different from polymorphism?
Polymorphism: function with the same name but different signatures. Templates: function name is the same, and signatures are different (aren't they?) Example: a function that sums two numbers. I can have two integers going into the function and another integer coming out. I can do the same with double or float or long. So isn't this polymorphism? Thank you for your time 🙂
3 odpowiedzi
+ 12
Templates could be called "compile time polymorphism" because the compiler replaces the template space with the proper code.
+ 4
After some searching and reading I arrived at this conclusion:
Polymorphism, at its core, has nothing to do with derived classes. Polymorphism simply means the ability to use a type without knowing everything about it. Rather than using a concrete type, polymorphism relies on some form of prototype to define what types it takes. Any types that fit that prototype are accepted.
Runtime polymorphism, in C++, is provided by deriving classes from a base class that contains virtual functions. The base class and virtual functions form the polymorphic prototype. Code written to accept the base class that calls these virtual functions will accept any class instance derived from the base class.
Compile-time polymorphism is polymorphism that happens... at compile time ;) What this means is that the compiler must know what is going on. You may have written the C++ code against a polymorphic prototype, but the compiler doesn't care. You get specific concrete types post-compilation.
Compile-time polymorphism is provided by templates in C++ (thank you @Helioform)
Correct me if I'm wrong somewhere... 🙂
+ 2
@Helioform thanks ☺
Some aspects are clear 👍