answersLogoWhite

0

Templates allow us to reduce the need to write duplicate code ourselves and force the compiler to duplicate the code for us. This saves a great deal of time (and money) and greatly reduces code maintenance because there's only one version of the implementation to modify. This greatly reduces the chances of us making a mistake because the compiler will propagate all the changes for us. Moreover, we don't need to second-guess what data types we might need to cater for in the future because the compiler will generate specific versions on an as-required basis, according to the types we actually use -- including those we haven't yet designed!

You've probably been taught that code duplication is a bad thing -- and you'd be right -- but it is also a necessary evil. The difference with templates is that rather than placing the onus upon the programmer to ensure the code duplication is consistent, the onus is placed entirely upon the compiler.

So when do we need code duplication? We need it whenever the implementation of a function or a class differs only in the type of data they operate upon. That is, one class or function definition that caters for any data type, rather than creating many separate classes or functions for each data type. If the implementations are exactly the same in every way, then duplicate code is inevitable. It's simply a matter of whether we write it ourselves and accept all the pitfalls that come with that, or we let the compiler do all the donkey work for us. The latter is always the preferred option every time.

Consider the following simple example:

int max(int a, int b){ return(a

double max(double a, double& b){ return(a

foo& max(foo& a, foo& b){ return(a

As you can see, all three functions have exactly the same implementations, they only differ in the type of data they operate upon. This is where templates come in. If we replace the data type with a template parameter then we need only define the function once:

template

T max(T a, T b){ return(a

Note that T is a standard token for a template parameter. If we needed more than one data type in the same function or class then we'd use tokens T1, T2, etc. The compiler will replace these tokens with the actual data type we supply at compile time.

Now when we call max(), the compiler will generate the appropriate overload for us at compile time, provided both arguments are covariant (are of the same intrinsic type). Thus the following are acceptable calls to max():

int x=42;

int y=2112;

int z=max(x,y); // z==2112

std::string s1("hello");

std::string s2("world");

std::string s3=max(s1,s2); // s3=="world"

It should be noted that since templates are incomplete types, the implementation must be made visible to the compiler BEFORE encountering any usage of the template for the first time. Thus you must either define the function within the declaration, or outside of the declaration but within the same file or #include the file containing the definition immediately after the declaration. If defining outside of the declaration, remember to also include the template:

// declaration...

template

T max(T a, T b);

// definition...

template

T max(T a, T b) { return(a

The same principal applies to classes where one or more data members employ template parameters. However, you must include the template keyword in every member method defined outside of the class, including the class constructors, as per the following example:

template

class foo

{

public:

foo(const T data):m_data(data){}

foo(const foo&); // defined externally...

private:

T m_data;

};

template

foo::foo(const foo& f): m_data(f.m_data) {}

Whenever you instantiate any objects from a template class, you must also provide the data type(s) so the compiler knows how to generate the complete class definition. For example:

foo f1(42);

foo f2("Hello World");

Now that you have a basic understanding of templates, you should find working with the STL containers (including std::list and std::vector) that much easier.
A template is an incomplete type. Template functions can be likened to overloaded functions where the implementation is exactly the same, the only difference being the type of argument or arguments passed to the function. For instance, when determining the larger of two objects of the same type, the implementations would be the same regardless of the type, like so:

int& max(int& x, int& y){ return(y

float& max(float& x, float& y){return(y

Since this function can be applied to any object that supports the less-than operator, writing all the overloads by hand places a heavy burden upon the programmer. Every time the programmer creates a new object that supports the less-than operator, they would have to write a new overload to cater for it.

C++ templates make it much simpler by allowing the programmer to define the function just once, using template parameters instead of formal arguments, like so:

template

T& max(T& x, T& y){ return(y

When you call the max function, the compiler automatically generates the appropriate overload for you (unless one was already generated by an earlier call with the same type).

Function templates can also be used within classes (template methods). In this case, the compiler generates separate overloads for each method within the class according to the types passed to those methods.

However, if the class contains a template data member, the compiler generates separate classes for each type. This is known as a template class.

The following code demonstrates all these concepts:

#include

// template function:

template

T& max(T& x, T& y){ return( y

// template method:

struct A

{

template

T& max(T& x, T& y){ return( y

};

// template class:

template

struct B

{

T data;

const bool operator< (const B& b){ return( this->data

};

template

std::ostream& operator<< (std::ostream& os, const B& b) { os<

int main()

{

int i1=24, i2=42;

double d1=4.2, d2=2.4;

A a;

B bi1; bi1.data=i1;

B bi2; bi2.data=i2;

B bd1; bd1.data=d1;

B bd2; bd2.data=d2;

std::cout<<"Calling template function:\n"<

std::cout<<"The maximum of "<

std::cout<<"The maximum of "<

std::cout<

std::cout<<"Calling template method of class A:\n"<

std::cout<<"The maximum of "<

std::cout<<"The maximum of "<

std::cout<

std::cout<<"Calling template function with template class B types:\n"<

std::cout<<"The maximum of "<

std::cout<<"The maximum of "<

std::cout<

std::cout<<"Calling template method of class A with template class B types:\n"<

std::cout<<"The maximum of "<

std::cout<<"The maximum of "<

std::cout<

}

Output

Calling template function:

The maximum of 24 and 42 is 42

The maximum of 4.2 and 2.4 is 4.2

Calling template method of class A:

The maximum of 24 and 42 is 42

The maximum of 4.2 and 2.4 is 4.2

Calling template function with template class B types:

The maximum of 24 and 42 is 42

The maximum of 4.2 and 2.4 is 4.2

Calling template method of class A with template class B types:

The maximum of 24 and 42 is 42

The maximum of 4.2 and 2.4 is 4.2

Note that there is only one class A type, and that it contains two overloads of the max function. However there are two class B types (one for int, the other for double). Thus although you could assign bi1 to bi2 because they are the same type, you cannot assign bi1 to bd1 because they are different types.

User Avatar

Wiki User

11y ago

What else can I help you with?

Continue Learning about Engineering

What is the program to create a string class which stores a string value in c plus plus?

C++ already provides a string class in the C++ standard template library. #include&lt;iostream&gt; #include&lt;string&gt; int main() { using namespace std; string s {"Hello world!"}; cout &lt;&lt; s &lt;&lt; endl; }


Distinguish between class template and template class?

Template class: A generic definition or a parametrized class not instantiated until the client provides the needed information. It?s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It?s jargon for plain classes. Class template is a template used to generate template classes. We cannot declare an object of a class template. Template class is an instance of a class template.


What is default name of c plus plus?

If you mean the original name of C++, it was originally called "C with Classes". However, after the introduction of template metaprogramming, it was renamed C++ which meant "the successor to C".


What is a Concrete class in c plus plus?

A concrete class is a complete type, as opposed to an abstract class which is an incomplete type.class A {public:virtual void f () = 0; // pure-virtual; class A is abstract// ...};class B : public A {public:void f () override; // overrides A::f(); class B is concrete};class C {// no pure-virtual methods; C is a concrete type// ...};Template classes are generic types. We usually evolve a generic type from a concrete type rather than write a template class from scratch, a technique known as lifting. The concrete type provides us with the complete implementation which is useful for testing and debugging purposes. When the concrete class is fully-implemented and error-free, we can generalise to produce the generic type.


What is nested class in c plus plus?

s.

Related Questions

What has the author Mark Nelson written?

Mark Nelson has written: 'C++ programmer's guide to the standard template library' -- subject(s): C++ (Computer program language), Standard template library, C. 'C [plus plus] programmer's guide to the Standard Template Library' -- subject(s): C.


What is the program to create a string class which stores a string value in c plus plus?

C++ already provides a string class in the C++ standard template library. #include&lt;iostream&gt; #include&lt;string&gt; int main() { using namespace std; string s {"Hello world!"}; cout &lt;&lt; s &lt;&lt; endl; }


How to write C plus plus Program to take 2 distant values as argument and return the larger value on the screen?

Use the following template function: template&lt;class T&gt; T&amp; max(T&amp; x, T&amp; y){return(y&lt;x?x:y;}


Can a c plus plus class be derived from a Java class?

No.


Distinguish between class template and template class?

Template class: A generic definition or a parametrized class not instantiated until the client provides the needed information. It?s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It?s jargon for plain classes. Class template is a template used to generate template classes. We cannot declare an object of a class template. Template class is an instance of a class template.


What are the similarities between c plus plus and java?

C++ and Java are identical except for...No pointers in JavaAll object names are referencesNo operator ->, only operator .No multiple inheritance in JavaNo template classes in JavaThe run-time and class libraries are vastly different


What is default name of c plus plus?

If you mean the original name of C++, it was originally called "C with Classes". However, after the introduction of template metaprogramming, it was renamed C++ which meant "the successor to C".


What is the role of object in c plus plus?

An object in C++ is an instance of a C++ class.


What is a Concrete class in c plus plus?

A concrete class is a complete type, as opposed to an abstract class which is an incomplete type.class A {public:virtual void f () = 0; // pure-virtual; class A is abstract// ...};class B : public A {public:void f () override; // overrides A::f(); class B is concrete};class C {// no pure-virtual methods; C is a concrete type// ...};Template classes are generic types. We usually evolve a generic type from a concrete type rather than write a template class from scratch, a technique known as lifting. The concrete type provides us with the complete implementation which is useful for testing and debugging purposes. When the concrete class is fully-implemented and error-free, we can generalise to produce the generic type.


What is nested class in c plus plus?

s.


What is the unit of programming in c plus plus A. Function B. class C. object D. Attribute?

B. Class.


What is a method in c plus plus?

In C++, methods are simply class member functions.