Tuesday, November 24, 2015

generic programming

Generic programming is about generalizing software components so that they can be easily reused in a wide variety of situations. In C++, class and function templates are particularly effective mechanisms for generic programming because they make the generalization possible without sacrificing efficiency.


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 goal of generic programming is to write code that is independent of the data types. In C language, all codes are tied to a specific data type. For container data structures (such as array and structure), you need to specify the type of the elements. For algorithms (such as searching or sorting), the code works only for a specific type, you need to rewrite the code for another type. Can we write a single sorting routine that works on all types (or most of the types) by specifying the type during invocation? Can we have a general container that can work on all types?
Template lets you program on generic type, instead of on a specific type. Template supports so-called parameterized type - i.e., you can use type as argument in building a class or a function (in class template or function template). Template is extremely useful if a particular algorithm is to be applied to a variety of types, e.g., a container class which contains elements, possibly of various types.

Function Template

function template is a generic function that is defined on a generic type for which a specific type can be substituted. Compiler will generate a function for each specific type used. Because types are used in the function parameters, they are also called parameterized types.
The syntax of defining function template is:
template <typename T> OR template <class T>
return-type function-name(function-parameter-list) { ...... }

Class Template

The syntax for defining a class template is as follow, where T is a placeholder for a type, to be provided by the user.
template <class T>    // OR template <typename T>
class ClassName {
   ......
}
The keywords class and typename (newer and more appropriate) are synonymous in the definition of template.
To use the template defined, use the syntax ClassName<actual-type>.

No comments:

Post a Comment