You are on page 1of 6

Generic Programming, Function and Class Template

Why Generic
Programming?
Generic
Programming
Benefits and Basics
Applications Presentation
Function
Type alias,
Alias Template
Function Template Template Assignments

Generic References
Class Template Programming, Codes
Function and
Class
Template
Type Alias,
Alias Template
Class
Template Function
Specialization Template
Class Specialization
Template
Why Generic Programming?
Consider the case of a linked list data structure being developed. Currently if the data item is an
employee information, then this becomes unusable when data changes. Hence there is a need to build a
data type independent linked list data structure which can use any data type at backend. This requires the
data to be treated as void * which can be type casted at runtime and used accordingly. This kind of
programming is known as generic programming.
Generic programming is a style of computer programming in which type is specified as a parameter to a
method, class or interface and the datatype is delayed until instantiation.
Video #1. Generic programming in 2 mins

Benefits

• Code reusability
• Avoid function overloading
• Write once and use many times
• Isolate data from algorithm
• Eliminate complexity and makes it simple to use
Applications

• All containers like vector, array, list etc


• Graph Algorithms
Template Basics
Function and class templates are used to achieve Generic Programming. Functions template is an
example for compile time polymorphism.
Use of keyword template tells the compiler that function or class definition that follows will manipulate
one or more unspecified data types.
Function Template
Allows to create new functions based on type parameters.

template <typename X> template <class X, class Y>


void swap(X &a, X &b) Y *myfunc(X *arg1, X &arg2, Y arg3)
{ {
X temp; arg3++;
temp = a; arg2+=10;
a = b; return arg3;
b = temp; }
}

Function Template with Default Arguments

template <class X, class Y>


Y *myfunc(X *arg1, X &arg2, Y arg3=10)
{
arg3++;
arg2+=10;
return arg3;
}
Function Template with Specialization
Extended version of function template with separate implementation for one or more specific data
type(s).
Note: Function template specialization with default parameter is not allowed

template <class X>


X add(X v1)
{
X tot = 0;
tot += v1;
return tot;
}
template <>
char add<char>(char v1)
{
char tot = ‘A’;
tot += v1;
return tot;
}

Video #2. Template Specialization (template function with specialization)

Do you want to know more about Function template working?

Optional Video #3. C++ Function Templates: How Do They Really Work? - Walter E. Brown

Perfect Forwarding
If a function template forward its arguments without changing its lvalue or rvalue characteristics, then it is known
as Perfect forwarding.

// perfectForwarding1.cpp
#include <iostream>

template <typename T,typename Arg>


T create(Arg& a){
return T(a);
}

int main()
{
// Lvalues
int five=5;
int myFive= create<int>(five);
std::cout << "myFive: " << myFive << std::endl;

// Rvalues
int myFive2= create<int>(5);
std::cout << "myFive2: " << myFive2 << std::endl;
}
Benefits of Perfect Forwarding

➢ Avoids excessive copying


➢ Avoids the template author having to write multiple overloads for lvalue and rvalue references.
Know more on perfect forwarding?

Class Template
A class using templated data type. Class may consist of the member function and data members of
templated data types. The actual data type is known at the time of instantiation.

template <class T> template <class T>


class Myclass void Myclass<T>::getData(T *dout)
{ {
public: *dout = *data+10;
Myclass()int sz = 1):count(sz) }
{ int main()
data = new T[sz]{10}; {
} //instantiating an int type
void getData(T *data); Myclass<int> myobj(2);
~Myclass(){//To Delete memory} int data;
private: myobj.getData(&data);
int count; //int size }
T *data;
};

Video #4. (animated video and no audio) class with templated functions

Class Template with specialization


Redefinition of the templated class for each specific data type.

template <class T>


class Myclass<int>
{
public:
Myclass(int sz = 1):count(sz)
{
data = new int[sz]{5};
}
//specialized handling for integer
void getData(int *dout)
{
*dout = *data+10;
}

private:
int count; //int size
int *data;
};
Type Alias
Type alias is a name that refers to a previously defined type (similar to typedef).

• Type alias is used to overcome the error in typedef due to incorrect order
o typedef int myint //incorrect typedef
• Used to help with legibility and documentation
• Used to write platform independent coding

testScore_t GradeTest();
using testScore_t = int;
// type alias for function pointer
using func = void (*) (int, int);
#ifdef INT_2_BYTES
void example(int, int) {}
using int8_t = char;
using int16_t = int;
int main()
using int32_t = long;
{
#else
Int8_t var = 0x01;
using int8_t = char;
testScore_t x = 90;
using int16_t = short;
using int32_t = int;
func f = example;
#endif
}

Alias template

• Alias template is a name that refers to a family of types.


• Feature available from C++11 onwards
• It is a template which, when specialized, is equivalent to the result of substituting the template
arguments of the alias template

// alias template
template<class T>
using ptr = T*;

// the name 'ptr<T>' is now an alias for pointer to T


ptr<int> x;

Summary

• Use function and class templates to develop and reuse data independent code algorithms/business
logic.
• For specialized data handling, use function/class templates with specialization.
• Function templates can use default arguments too.
• Instead of typedef use type alias to enhance legibility and documentation
• Use alias template with templates
Reference Codes

Presentation

Assignments

C++ Libraries

C++ Template Guidelines

C++ Styleguide

C++ Template FAQ

You might also like