answersLogoWhite

0


Best Answer

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

10y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

9y ago

A template allows the compiler to generate function overloads and/or class definitions from a generic implementation that differs only by type. The standard template library provides many examples of templates. For instance, std::vector is a template that implements a dynamic array for any given type. Rather than declare separate vector implementations to cater for the infinite number of types that might exist in a vector, a template provides a single generic implementation from which the compiler can generate the precise classes that are actually used by the programmer. This not only reduces code size, it makes maintenance easier since all code is available from a single source rather than duplicated across multiple sources. Templates can also be specialised to cater for more specific types, such as catering for the difference in the way C++ treats a value and a pointer to a value. The specialisation need only cater for the differences.

Functions are the simplest form of template and can be applied to class methods as well as standalone functions. When you have several function overloads where the implementation is exactly the same, the only difference being the type of the arguments and possibly the function type, it makes sense to define the function once and let the compiler generate the overloads for you. For instance:

template<typename T>

T max (T a, T b) { return a < b ? b : a; }

In the above function, the template argument T acts as a token which will be replaced by the type you supply to the function:

int w = max (42, 32);

size_t x = max (42U, 32U); float y = max (3.14f, 42.0f);

double z = max (3.14, 42.0);

In other words, the compiler generates the following overloads:

int max (int a, int b) { return a<b?b:a; }

size_t max (size_t a, size_t) { return a<b?b:a; }

float max (float a, float b) { return a<b?b:a; }

double max (double a, double b) { return a<b?b:a; }

Note that all the overloads have the exact same implementation (as determined by the template); only the type of the arguments and the return type differ.

The same can be applied to classes, however you must supply the typename as part of the declaration of an instance of the class:

template<typename T>

struct foo {

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

T m_data;

};

// Declare instances of foo:

foo<int> f (42);

foo<size_t> f (42U);

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

A template is a function or class for which the implementation only differs by type. It is a way of providing generic implementations that can cater for any given type, rather than having to write each implementation separately for specific types. This helps to reduce unnecessary code duplication and thus reduces maintenance costs. The C++ standard template library (STL) makes extensive use of templates. Specific functions and classes are only generated for those types you actually use.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

A function template is an overloaded function where every overload has the exact same implementation but differs in the type of arguments you pass to the function. Rather than writing each overload by hand, which would require duplicate code for each type you wish to handle and increased maintenance whenever you wish to cater for a new type, the compiler generates the overloads for you, on an as-required basis, swapping the template arguments for the types you pass. Even the return type can be a template, but it must be the same as one argument type, typically the first argument.

A good example is the max function which returns the greater of two values. Since values could be represented by char, short, long, float or double, or even an user-defined type or complex type, such as a class, the number of overloads required to cater for all possibilities would be huge. With a template function you only need one function, which reduces code duplication and minimises maintenance. The same can be said of the min function, or any function that only differs in the type of argument it accepts.

template<typename T>

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

{

return( y<x?x:y );

}

In the above example, the typename, T, is substituted with the actual types you pass. Thus if you pass two int values, a function with the signature int& max(int&, int&) is generated for you. If you pass two float values, T is substituted with float, and so on. Thus the overloads that are generated are entirely dependent upon the calling code, you don't need to write overloads that may never be used.

int main()

{

int a=4, b=2, c;

c = max(a,b); // c==4

float d=4.0, e=0.2, f;

f=max(d,e); // f==4.0

}

Note that although you can achieve the same sort of thing using macro functions (which are always inline expanded), template functions are type safe and will only be inline expanded when there is an advantage in doing so. And since they are part of the language itself, template functions can be debugged like any other function, whereas macro functions cannot (the preprocessor inline expands macro functions in the intermediate source, thus all macros are eliminated before the compiler sees them).

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

A template in C++ is a piece of code, usually a class declaration and definition, that contains non type specific code. It has "markers", instead, that are replaced by the compiler when the instantiation of an object takes place. These markers, very much like macros, allow you to write a class that does not have to deal with a specific type, and then to reuse that class for different types.

A classic example is a "smart pointer", used to solve virtual memory heap fragmentation similarly to how it is done natively in JAVA. You create a smart pointer to an integer, for example, and debug it and get it working. Now you want a smart pointer to a float, or worse, some monstrous class. Instead of taking a copy of the code and revising it, you use the original code and change the marker. Often, the marker is <T>, but it can be anything you want.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

There are two types of template in C++; template functions and class templates.

Template functions are functions for which the implementation remains exactly the same regardless of the type of argument(s) passed to it. Rather than writing all the possible overloads by hand, a template function places the onus upon the compiler to generate the required overloads for you, automatically, according to the type of arguments passed to the function.

Typical examples are the std::max and std::min functions, which are defined as follows:

template<typename T>

T& std::max(T&x,T&y)

{

return(x<y?y:x);

}

template<typename T>

T& std::min(T&x,T&y)

{

return(x<y?x:y);

}

So long as the arguments you pass to these functions are of the same type, T, and that type implements a less than operator overload, then these two definitions will cater for any type, whether they be integral primitives or complex objects. The compiler will only generate the necessary overloads for the calls you actually invoke.

Note that uppercase T is used by convention to denote a template type. However, any token or symbol can be used. All occurrences of that symbol will be replaced by the compiler with the actual type passed to the function. You may also cater for mixed types using a comma-separated list, each with a different token. However, keep in mind that if the return type is itself a template, it must match with one of the argument types, and may introduce ambiguity. For instance:

template<typename T1, typename T2>

T1& foo(T1&x,T2&y)

{

// ...

return(x);

}

If you were to call foo(int, float), the return value would be an int. But if you were to call foo(float,int), the return would be a float. Thus the order of the arguments ultimately determines the return type, which is ambiguous. In these cases it is often better to use output parameters and use the return value to indicate any error conditions.

Class templates are similar, insofar as any member function may be a template function. However, any data member of the class may also be a template type, and the compiler will generate different classes for each type you specify when instantiating an object of the type. The std::vector is a typical example of a class template, which allows you to generate dynamic arrays of any type. To instantiate a vector of type int, you would use the following syntax:

std::vector<int> my_vector;

The bare bones of a class template declaration are as follows:

template<typename T>

class foo

{

private:

T m_data;

};

Note that class templates must be defined in the same file as their declarations. This is because class templates are incomplete types and the compiler must have access to the entire definition before encountering any code that instantiates a complete class with a specific type.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Templates allow you to create one function or class that caters for different data types, without having to duplicate the implementation to cater for each data type independently. The compiler will generate the required functions and classes for you, according to the actual data types you use (including those you haven't yet created). This reduces maintenance as you only need to maintain code in one place, rather than copy/paste changes to all instances, which may introduce errors if you forget to propagate all changes throughout your code. The compiler effectively takes care of all that work for you, thus reducing your overall workload.

This answer is:
User Avatar

User Avatar

Wiki User

7y ago

A template class is a generic class in much the same way that a template function is a generic function. We use templates extensively in C++ because it greatly reduces the amount of duplicate code we need to write. If we consider a simple container class such as a list, we ideally want to instantiate lists of a specific type, such as a list of integers or a list of strings. If we need to cater for more than one type (such as different types of shape), then we simply instantiate a list of abstract data types where the actual types are derived from a common abstract base class. But in order to create lists of different types we'd need to define separate classes to deal with each type. Imagine if our program had 100 different types and we had to implement 100 different list classes in order to cater for each of them individually.

However, if we think of a list in more generic terms, the only thing that actually differentiates one type of list from another is the type of object we can place in the list. By using a template parameter to represent that type we only need to define one class, and that one class can cater for any type of object, including those we haven't yet defined!

Whenever we use a template parameter in a function or a class, we enlist the help of the compiler to generate code for us, thus we greatly reduce the amount of duplicate code we need to write; the compiler does it for us. Code duplication at the machine level is unavoidable, however by shifting the onus of responsibility to the compiler, our source code becomes much easier to maintain. If we need to change the implementation of our list, we only need to make that change in one place: in the template class. The compiler will automatically generate new code for us.

More importantly, the compiler only generates code for the class members that we actually use. Although we should generally avoid writing code that is never used, we don't pay the price for unused code within a class template. More commonly, if we instantiate two or more different types from the same template but only one of those types makes use of a particular class member, then that method will not be replicated in the other instances. By the same token, when we instantiate two or more objects of the same type from a template, the code generated is the same for all instances, depending on the combined members used by all instances.

In addition, we can also use compile-time computation to provide constraint-checks upon our template parameters. For instance, if a template class should generate code for integral types but not for floating point types, then we can use compile time computation to provide meaningful compile-time error messages.

Template classes can also be specialised to cater for more specific types. We typically use specialisation to cater for pointer types as these usually require more specific handling than the more general types do. Specialisations can be complete or partial. For instance, we might provide a complete specialisation to cater for all pointer types (void*) plus one or more partial specialisations to cater for more specific pointer types.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What is a template class in c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
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;}


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.


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

No.


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.