Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ Conditions C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ Data Structures

C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime>

C++ Examples

C++ Examples C++ Compiler C++ Exercises C++ Quiz C++ Certificate


C++ Templates


C++ Templates

Templates are a way to allow functions and classes to use the same code for many different data types.

To declare a template you use the template keyword followed by a list of template parameters in angle brackets:

template <parameter1, parameter2, parameter3>

Immediately after the template declaration, you write a function or class definition the normal way. The function or class will have access to special data types and values given by the template declaration.

Example

Use a template to create a class that can use any data type:

template <class MyType>
class MyClass {
  public:
    MyType first;
    MyType second;

    MyClass(MyType f, MyType s) {
      first = f;
      second = s;
    }
};

int main() {
  // Use MyClass with strings
  MyClass<string> stringObj( "Hello", "World" );
  cout << stringObj.first << " " << stringObj.second << "\n";

  // Use MyClass with integers
  MyClass<int> intObj( 4, 5 );
  cout << intObj.first << " " << intObj.second << "\n";

  return 0;
}
Try it Yourself »

Example explained

  • The first line template <class MyType> declares the template
  • class MyType is a template parameter that makes MyType possible to represent any data type. You will learn about template parameters in the next chapter.
  • MyClass<string> stringObj( "Hello", "World" ); creates a MyClass object where MyType means string
  • MyClass<int> stringObj( 4, 5 ); creates a MyClass object where MyType means int

C++ Template Parameters

Template parameters are how you specify how many data types and values a template has access to.

There are two kinds of template parameters: typed parameters and non-typed parameters.


Typed Parameters

Typed parameters allow you to specify a "wildcard" data type for a class or function.

A typed parameter uses the keyword class or typename followed by a name. There is no difference between the class and typename keywords, you can use any one of them.

The syntax of a template with typed parameters looks like this:

template <class A, class B>

The following example declares two different typed parameters:

Example

template <class A, class B>
class MyClass {
  public:
    A first;
    B second;

    MyClass(A f, B s) {
      first = f;
      second = s;
    }
};

int main() {
  MyClass<int,string> myObj( 15, "Some Text" );
  cout << myObj.first << " " << myObj.second << "\n";
  return 0;
}
Try it Yourself »

Example explained

  • The line template <class A, class B> indicates that there are two different data types which are assigned the names A and B
  • A first; creates an attribute named first of type A
  • B second; creates an attribute named second of type B
  • The constructor MyClass(A f, B s) has two parameters: f is of type A and s is of type B
  • The line MyClass<int,string> myObj( 15, "Some Text" ); creates a MyClass object where A means int and B means string.

Non-Typed Parameters

Non-typed parameters let you pass values directly to the class or function that is using the template.

To add a non-typed parameter, write the data type of the value followed by a name. The syntax looks like this:

template <dataType1 name1, dataType2 name2>

This example declares a class with a non-typed parameter:

Example

template <int N>
class MyClass {
  public:
    string myStrings[N];
};

int main() {
  MyClass<2> myObj;
  myObj.myStrings[0] = "Hello";
  myObj.myStrings[1] = "World";

  cout << myObj.myStrings[0] << " ";
  cout << myObj.myStrings[1] << "\n";

  return 0;
}
Try it Yourself »

Example explained

  • The line template <int N> indicates that the parameter N contains an integer.
  • string myStrings[N]; uses the value of N to set the size of an array of strings.
  • MyClass<2> myObj; creates a MyClass object and sets the value of N to 2, which results in the myStrings array having 2 strings.

Another Example

This example illustrates how to use both typed and non-typed parameters in a template class:

Example

template <class T, int N>
class MyClass {
  public:
    T myArray[N];
};

int main() {
  // Using string data type and 2 elements
  MyClass<string, 2> stringObj;
  stringObj.myArray[0] = "Hello";
  stringObj.myArray[1] = "World";

  cout << stringObj.myArray[0] << " ";
  cout << stringObj.myArray[1] << "\n";

  // Using int data type and 4 elements
  MyClass<int, 4> intObj;
  intObj.myArray[0] = 2;
  intObj.myArray[1] = 4;
  intObj.myArray[2] = 6;
  intObj.myArray[3] = 8;

  cout << intObj.myArray[0] << " ";
  cout << intObj.myArray[1] << " ";
  cout << intObj.myArray[2] << " ";
  cout << intObj.myArray[3] << "\n";

  return 0;
}
Try it Yourself »

Templates in


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.