Home arrow C++ arrow Page 7 - The Mighty C++ Template

The Mighty C++ Template

One of the biggest advantages of using C++ is templates. Templates were designed from the ground up to allow developers to write one function to handle many different types of parameters. In this article, Mitchell will explain what both function and class templates are, and give examples of each.

Author Info:
By: Mitchell Harper
Rating: 5 stars5 stars5 stars5 stars5 stars / 48
November 23, 2001
  1. · The Mighty C++ Template
  2. · Understanding function overloading
  3. · The template
  4. · The template (contd.)
  5. · A simple class template
  6. · A simple class template (contd.)
  7. · Instantiating the class
  8. · Behind the scenes
  9. · Conclusion

print this article

The Mighty C++ Template - Instantiating the class
(Page 7 of 9 )

Before we can use our class template, we must create an instance of it within our main function:

MyClass<int> mc(1, 2, 3);

cout << "Return value is: " << mc.GetAverage() << endl << endl;

On the first line, we are creating a new instantiation of our class template. Between the angled brackets, we are telling the C++ compiler that our class will be handling integer (int) type variables. This is a mandatory inclusion and the compiler will complain if you leave it out. The new instantiation of our “MyClass” template is called “mc”. We are passing three values to the default constructor, which will be stored as the private variables n1, n2 and n3. In our examples, these variables will be of type int, meaning T will take on the role of an integer.

On the second line above, we simply call the GetAverage() function of our class template, just like we would with any class, outputting the value returned from the function, which looks something like this:

Return value is: 2
blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials