Thursday, January 21, 2016

Generic programming

Generic programming means that you are not writing source code that is compiled as-is but that you write "templates" of source codes that the compiler in the process of compilation transforms into source codes. The simplest example for generic programming are container classes like arrays, lists or maps that contain a collection of other objects. But there's much more to generic programming. In the context of C++ .it means to write programs that are evaluated at compile time. A basic example of generic programming are templates of containers: In a statically typed language like C++ you would have to declare separate containers that hold integers, floats, and other types or deal with pointers to void and therefore losing all type information. Templates which are the C++ way of generic programming leverage this constraint by letting you define classes where one or more parameters are unspecified at the time you define the class. When you instance the template later you tell the compiler which type it should use to create the class out of the template. 

Example: template class MyContainer { // Container that deals with an arbitrary type T }; 

void main() 
{
 // Make MyContainer take just
 ints.  MyContainer intContainer;
 }

No comments:

Post a Comment